﻿// ==UserScript==
// @name           Magic Elite
// @version        2C.2  10*16*2013
// @namespace      MAD_HATTER
// @icon           https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRHiyOmpheJ6VSr-H6c0OLSZSitQkQzkiUbPo0MDsKZTRIFrCSmaA
// @description    Kingdom of Camelot 
// @homepage       http://koc-power-all.webs.com/

// @include        *kingdomsofcamelot.com/*main_src.php*
// @include        *kingdomsofcamelot.com/*fbLoginButton.php*
// @include        *kingdomsofcamelot.com/*standAlone.php*
// @include        *kingdomsofcamelot.com/*platforms/kabam*
// @include        *kingdomsofcamelot.com/*acceptToken_src.php*
// @include        *kingdomsofcamelot.com/*helpFriend_src.php*
// @include        *kingdomsofcamelot.com/*newgameV2_src.php*
// @include        *apps.facebook.com/kingdomsofcamelot/*
// @include        *facebook.com/connect/uiserver.php* 
// @include        *facebook.com/*/serverfbml*
// @include        *facebook.com/dialog/feed*
// @include        *facebook.com/dialog/stream.publish*
// @include        *facebook.com/dialog/apprequests*
// @include        *kabam.com/*

// @resource       en http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/en.js
// @resource       de http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/de.js
// @resource       es http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/es.js
// @resource       fr http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/fr.js
// @resource       gr http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/gr.js
// @resource       it http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/it.js
// @resource       pt http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/pt.js
// @resource       tr http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/tr.js
// @resource       SR http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/SR.js

// @resource       SYSTEM_TABS http://mad-hatters-magic-elite.googlecode.com/svn/beta/system/tabs.js
// @resource       SYSTEM_AVATAR http://mad-hatters-magic-elite.googlecode.com/svn/beta/system/avatars.js
// @resource       SYSTEM_IMAGES http://mad-hatters-magic-elite.googlecode.com/svn/beta/system/images.js

// @resource       PLUGIN_BUTTLER http://mad-hatters-magic-elite.googlecode.com/svn/beta/plugins/buttler.js
// @resource       PLUGIN_SOUNDS http://mad-hatters-magic-elite.googlecode.com/svn/beta/plugins/sounds.js
// @resource       PLUGIN_SMILEYS http://mad-hatters-magic-elite.googlecode.com/svn/beta/plugins/smileys.js
// @grant          unsafeWindow
// @grant          GM_getValue
// @grant          GM_setValue
// @grant          GM_addStyle
// @grant          GM_xmlhttpRequest
// @grant          GM_log
// @grant          GM_registerMenuCommand
// @grant          GM_getResourceText
// @grant          GM_getResourceURL
// @grant          GM_deleteValue
// ==/UserScript==

var Version = 'M_H ELITE EDITION'; 
var ScriptName = 'KoC Power All';
var releaseVersion=false; // false = Beta || true = Release
var LangpackVersion= '09/07/2013';
var KsVersionAlpha = 'beta'; // alpha || beta
var KsLangpackFolderId = '303';
var homePage="http://koc-power-all.webs.com/";
var uW = unsafeWindow;
var Seed = uW.seed;
var CM = uW.cm;
var searchblocks = 20;

var isChrome = (navigator.userAgent.toLowerCase().indexOf('chrome') > -1);
if (!isChrome) {
if(window.self.location != window.top.location){
   try{
      if(window.self.location.href == window.parent.location.href){
         return;
      }
   } catch (e){
   }
}
}
if(document.URL.indexOf('sharethis') != -1) {
   return;
};
if(document.URL.match(/standalone=1/i)){
    uW.appUrl = window.location.protocol+'//www.kabam.com/games/kingdoms-of-camelot/play?s='+uW.g_server;
 } else {
	uW.appUrl = window.location.protocol+'//apps.facebook.com/kingdomsofcamelot/?s='+uW.g_server;
 };
function ById(id) {return document.getElementById(id);}

var MAP_DELAY = 1300;
var DETECT_LEVEL_FS = false;
var JSON2 = JSON;
var RPM = 0;
var RPMtime = unixTime();

// QUICKFIX
/** <HOTFIX DetectLoadError> **/
if(/.*kingdomsofcamelot\.com\/.*main_src\.php.*/.test(window.location.href)) DetectLoadError();
function DetectLoadError(){
	var elmt=document.getElementById("errorPageContainer");
	if(elmt!=null) {
		logit("DetectLoadError: WARNING Auto reload because error page detected.");
		history.go(0);
		return;
	}
	elmt=document.getElementById("topnavDisplayName");
	if(elmt!=null) {
		logit("DetectLoadError: KoC loaded")
		return;
	}
	setTimeout(function(){DetectLoadError();},5000);
}
/** </HOTFIX DetectLoadError> **/

// SYSTEM FILES
eval(GM_getResourceText( 'SYSTEM_IMAGES' ));
eval(GM_getResourceText( 'PLUGIN_SOUNDS' ));


//    ÃƒÂ¢Ã¢â‚¬?Ã…â€™ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã‚?
//    ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡                                                              KOC POWER - STUFF                                                 ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡
//    ÃƒÂ¢Ã¢â‚¬?Ã¢â‚¬?ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã¢â€šÂ¬ÃƒÂ¢Ã¢â‚¬?Ã‹Å“

// LANGUAGE
var langpacks = {"en" : true, "de" : true, "fr" : true, "it" : true, "tr" : true, "es" : true, "gr" : true, "pt" : true};
var LangOptions = {	culang : 'en',	langpacks : {"en" : true, "de" : true, "fr" : true, "it" : true, "tr" : true, "es" : true, "gr" : true, "pt" : true},};
readLangOptions();
LangOptions.langpacks = langpacks;
if (LangOptions.culang.length != 2) LangOptions.culang = "en";
var culang;
if (!langpack) { var langpack = new Object() };
langpack.loaded = false;
eval(GM_getResourceText( LangOptions.culang ));
culang = langpack;
culang.doTranslate=function(text){
	// Replaces alle placeholders in text with corresponding values from culang
	// {%key%}  == culang.key

	var pattern=/{%([a-z0-9_$]+)%}/gi;
	var keys=Array();
	while (result = pattern.exec(text)) {
		var key=result[1];
		//GM_log(key);
		var found=false; for(var i=0;i<keys.length;i++){if(keys[i]==key){found=true;break;}}
		if(found) continue;
		keys.push(key);
	}
	var s=text;
	for(var i=0;i<keys.length;i++){
		var key=keys[i];
		if(typeof(culang[key])=="undefined") {
			logit("WARNING: Missing translation! 'culang."+key+"' Language: '"+LangOptions.culang+"'");
			continue;
		}
		var exp=new RegExp("{%"+key+"%}","g");
		s=s.replace(exp,culang[key])
	} return s; 
}
// MULTILANGUAGE STRING RESSOURCE kocpdx.SR.js
if(document.body.id == 'mainbody'){
	var SR={languages:["en","de","fr","it","tr","es","se","nl"]};
	for(var iSL=0;iSL<SR.languages.length;iSL++){SR[SR.languages[iSL]]={};}
	SR.getArray=function (entryKey, defLang){
		var tkArray=new Array();
		var tkLangArray2=[defLang].concat(SR.languages);
		for(var tkL=0;tkL<tkLangArray2.length;tkL++){
			var tkLang=tkLangArray2[tkL];
			if(typeof(SR[tkLang])==="undefined") continue;
			for(var tkX=1;;tkX++){
				if(typeof(SR[tkLang][entryKey+"_"+tkX])==="undefined") break;
				tkEntry=SR[tkLang][entryKey+"_"+tkX];
				tkExist=false;
				for(var tkAi=0;tkAi<tkArray.length;tkAi++){
					if(tkArray[tkAi]===tkEntry){tkExist=true;break;}
				}
				if(tkExist) continue;
				tkArray.push(tkEntry);
			}
		} return tkArray;
	};
	try{eval(GM_getResourceText('SR'));SR.loaded=true;}
	catch(ex){
		GM_log("ERROR: loading kocpdx.SR.js"+"\n"+ex);
		srErrDiv=document.createElement("div");
		srErrDiv.innerHTML="ERROR loading kocpdx.SR.js!";
		srErrDiv.setAttribute("style","background:yellow");
		document.body.insertBefore(srErrDiv, document.body.firstChild);
	}
	GM_log("String resources loaded: "+(SR.loaded==true));

	// define 'en' fallback
	for (var srEntry in SR.en){
		if(srEntry.match(/_[0-9]+$/)) continue; // skip "array" entries "item_1,item_2"
		// GM_log("SR.en."+srEntry+"="+"'"+SR.de[srEntry]+"';");
		if(typeof(SR.de[srEntry])==="undefined")SR.de[srEntry]=SR.en[srEntry];
		if(typeof(SR.fr[srEntry])==="undefined")SR.fr[srEntry]=SR.en[srEntry];
		if(typeof(SR.it[srEntry])==="undefined")SR.it[srEntry]=SR.en[srEntry];
		if(typeof(SR.tr[srEntry])==="undefined")SR.tr[srEntry]=SR.en[srEntry];
		if(typeof(SR.es[srEntry])==="undefined")SR.es[srEntry]=SR.en[srEntry];
		if(typeof(SR.se[srEntry])==="undefined")SR.se[srEntry]=SR.en[srEntry];
		if(typeof(SR.nl[srEntry])==="undefined")SR.nl[srEntry]=SR.en[srEntry];
	}
}

// MAIN VAR
var ResetAll=false;var deleting=false;var ResetTabOptions=false;
var Recall=[];var WhatCity = 1;
var MarchesSend = 0;
var MarchesError = 0;
var MarchDelay = 6;
var MarchOffset = MarchDelay;
var Seconds = 0;
var provMapCoords = {imgWidth:710, imgHeight:708, mapWidth:670, mapHeight:670, leftMargin:31, topMargin:19};
var butON='<img align=absmiddle src="%3D" alt="'+culang.buttonON+'">';
var butOFF='<img align=absmiddle src="%3D%3D" alt="'+culang.buttonOFF+'">';
var DEFAULT_ALERT_SOUND_URL = 'https://koc-power-pdx.googlecode.com/files/RedAlert.ogg';
var SWF_PLAYER_URL = 'http://koc-power-pdx.googlecode.com/svn/beta/sounds/pdxminiplayer.swf';
var Cities = {};
var Tabs = {};
var my = {};
var Tabs2 = {};
var researchLevels = [];
var researchLevels2 = [];
var crestname = {};
// var CPopUpTopClass = 'ksPopTop';
var mainPop, mainPop2;
var ResetColors = false;var ResetDFOption = false;
var Tabs2=[["Production",culang.tabLabelProduction],["Inventory",culang.mainInventory],["Info",culang.mainInfo],["Alliance",culang.tabLabelAlliance],["Tournament",culang.tabLabelTournament],["Gifts",culang.mainGifts],["Resources",culang.tabLabelCourt],["Combat",culang.tabLabelCombat],["Ascension","Ascension"],["Spam","Spam"],["Fake",culang.tabLabelFake],["ActionLog",culang.tabLabelActionLog]]; 
var KsStartupTimer = null;
var currentName2 = 'Movement';
var myServerId = null;
var LastUnixTime = null;
var MapSearchActive = "";
// ptStartupErrorTimer = null;

// OPTIONS
var Options={MultiBrowser: true, showKsBadge:false,RPClip:1,KsSummonToggle:false,KDODef:0,KDOUser:{},SearchMightMin:0,SearchMightMax:9999,send2wave: false, merlinClose:false,AttackRunning:false,NewTab:false,KsHomeTab:false,NewTabURL:"http://www.your-url.com",NewTabName:"Chat",currentTab:null,currentTab2:"Overview1",reapprointerval:0,TSSrchFilter:0,KsTransparence:true,includeMarching:false,EnableFormation:false,showTroops:true,showPop:false,Smiley:true,showRes:true,SelQG:null,showProduction:true,showDefense:false,encRemaining:true,pbEveryEnable:true,pbEveryMins:60,KDODef:0,pbChatOnRight:false,pbWideMap:false,pbKillFairie:true,maxIdlePop:true,ChatLearder:true,voirRaid:false,WhisperOn:true,gmtClock:false,AttaqueOn:false,WildSoundOn:false,FoodSoundOn:false,EclaireurOn:false,srcSortBy:"level",EnableRefrechRapport:false,srcMinLevel:1,srcMaxLevel:10,srcTypeSelect:1,srcaDist:0,srcDist:20,Xrenfort:0,srcScoutAmt:1,PageReport:1,Yrenfort:0,icon_chatFlag:false,icon_chat:false,URLicon3:"http://kofc.god-like.info/multi/img/pdx-useravatar.png",filPuissance:0,filPuissanceMax:1e6,wildType:1,citySrchFilter:0,fixPageNav:true,mistedOnly:false,hostileOnly:false,fixTower:true,enhanceARpts:true,allowAlterAR:true,enableCheckTournoi:true,HauteurBoite:700,pbWinIsOpen:false,boTrackOpen:true,ptWin2IsOpen:false,ptWinDrag:true,ptWinPos:{},ptWin2Pos:{},enableFoodWarn:true,enableFoodWarnTchat:false,EnableReduireUnit:true,foodWarnHours:24,foodChatWarnHours:4,chatEnhance:true,fixKnightSelect:true,attackCityPicker:true,mapCoordsTop:true,dispBattleRounds:true,reportDeleteButton:true,arPageFrom:1,arPageTo:2,rptType:"alliance",rptAuto:false,alertSound:{enabled:true,soundUrl:DEFAULT_ALERT_SOUND_URL,soundUrlST:1,repeat:true,playLength:20,repeatDelay:.5,volume:100,alarmActive:false,expireTime:0},alertConfig:{changeThrone:false,throneSet:1,returnThrone:false,throneSetRet:1,returnThroneMin:60,aChat:true,raid:false,aPrefix:culang.optionsDefaultAlertMessage,scouting:true,wilds:true,defence:true,minTroops:1,minTroops2:1,embassy:false,fletching:true,marechal:true,defBoost:true,TroneRangeDebuff:false,TroneRange:false,mytroops:false,food:false,defense:true,MonQG:true,hq:"",sendasWhisper:false,sendtoAlly:true,showAttack:false,email:false},
	URLson1:"https://koc-power-pdx.googlecode.com/files/sonar.ogg",URLson1Vol:"100",URLson1ST:1,
	URLson2:"https://koc-power-pdx.googlecode.com/files/alarm.ogg",URLson2Vol:"100",URLson2ST:1,
	URLson4:"https://koc-power-pdx.googlecode.com/files/ding.ogg",URLson4Vol:"100",URLson4ST:1,
	URLson5:"https://koc-power-pdx.googlecode.com/files/slap.ogg",URLson5Vol:"100",URLson5ST:1,
	URLson6:"https://koc-power-pdx.googlecode.com/files/cartoon.ogg",URLson6Vol:"100",URLson6ST:1,
	buildUseSpeedups: false, throneUseSpeedups:false, TresureChestFB:true, multiUpdateSoundEnable:"1",multiUpdateSoundVol:"50",AttackHorloge:"21:00:00",AttackGoHorloge:null,AttackOnOff:false,AttackUnits:{},AttackFav:{0:{0:"200K "+culang.shrmilitiaman+"",1:0,2:2e5,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},1:{0:"200K "+culang.shrheavycavalry+"",1:0,2:0,3:0,4:0,5:0,6:0,7:2e5,8:0,9:0,10:0,11:0,12:0,13:0}},AttackFromCity:0,AttackCibleX:0,AttackCibleY:0,AttackKnight:0,TournoiLigne:25,AttackFSUnits:{1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0}},DeleteMsg:false,DeleteMsgs0:false,DeleteMsgs1:false,DeleteMsgs2:false,DeleteMsgs3:false,DeleteTimerMinute:5,giftDomains:{valid:false,list:{}},giftDelete:"e",HelpRequest:true,ChatRules:false,DeleteRequest:true,MapShowExtra:false,transportinterval:60,minwagons:1e3,lasttransport:0,reassigninterval:60,lastreassign:0,RaidRunning:true,RaidReset:0,MsgInterval:1,foodreport:false,Foodstatus:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	crestRunning:false,Crestinterval:5,CrestSlot:1,crestMarchError:0,CrestMsgInterval:24,Crest1Count:0,Crest2Count:0,crestreport:false,enhancedinbox : true,CrestLevel:0, CrestType:0,Creststatus:{1101:0,1102:0,1103:0,1104:0,1105:0,1106:0,1107:0,1108:0,1109:0,1110:0,1111:0,1112:0,1113:0,1114:0,1115:0,9:0,36:0,37:0,38:0,55:0,57:0,261:0,262:0,271:0,272:0,351:0,361:0,362:0,911:0,3000:0,3001:0,3002:0,3003:0,3007:0,3008:0,3009:0,3011:0,931:0,932:0},LastCrestReport:0,LastReport:0,spamOptions:{enableGlobal:false,spamMessageGlobal:culang.optionsDefaultSpamGlobalMessage,spamMinGlobal:"10",enableAlliance:false,spamMessageAlliance:culang.optionsDefaultSpamAllianceMessage,spamMinAlliance:"10",atimea:0,atime:0},
	EffetRouge:0,AllEffet:false,salvageconfig:{running:false,CityCity:0,RepairCity:0,Repairrunning:false,},TroneInverse:true,pbGoldEnable:false,enhanceViewMembers:true,showMightKoCBugFix : true, showResKoCBugFix : true,showKsInfoBox : false,customWideScreenSize:"1337", enableButtler:true, pdxMenuLeft:false, postMultiUpdate:false, pdxLangFlag:true, pdxHyperlinks:true, reloadIfCrestFaild : true, popupBorderRadius : "0px 0px 0px 0px",
	enableUserName1: false,userName1: "Lord PDX",enableUserName2: false,userName2: "Lady Darren Fohnstone",	enableUserName3     : false,		userName3		: "Lord Thomas Chapin",	enableUserName4     : false,		userName4		: "Lord George Jetson",	enableUserName5     : false,		userName5		: "Lord niknah",	enableUserName6     : false,		userName6		: "Lord DonDavici",	enableUserName7     : false, userName7	: "Lord Nico De Belder",	enableUserName8: false,userName8: "Lord jontey",enableUserName9: false,userName9: "Lord Darren Fohnstone",enableUserName10: false,userName10: "Lord PDX",enableUserName11: false,		userName11		: "Lord PDX",	enableUserName12     : false,		userName12		: "Lady Darren Fohnstone",	enableUserName13     : false,		userName13		: "Lord Thomas Chapin",	enableUserName14     : false,		userName14		: "Lord George Jetson",	enableUserName15     : false,		userName15		: "Lord niknah",	enableUserName16     : false,		userName16		: "Lord DonDavici",	enableUserName17     : false, userName17	: "Lord Nico De Belder",	enableUserName18     : false,		userName18		: "Lord jontey",	enableUserName19     : false,		userName19		: "Lord Darren Fohnstone",	enableUserName20	: false,		userName20		: "Lord PDX",	enableUserName21     : false,		userName21		: "Lord PDX",	enableUserName22     : false,		userName22		: "Lady Darren Fohnstone",	enableUserName23     : false,		userName23		: "Lord Thomas Chapin",	enableUserName24     : false,		userName24		: "Lord George Jetson",	enableUserName25: false,userName25: "Lord niknah",enableUserName26: false,userName26: "Lord DonDavici",	enableUserName27: false, userName27: "Lord Nico De Belder",enableUserName28: false,userName28: "Lord jontey",enableUserName29: false,userName29: "Lord Darren Fohnstone",enableUserName30:false,userName30:"Lord PDX",
	KsFunSoundAttack : false,soundURLF1 : 'https://koc-power-pdx.googlecode.com/files/siren.ogg',	URLsonF1vol : 100,URLsonF1ST:1,	
	KsFunSoundHorn : false,soundURLF2 : 'https://koc-power-pdx.googlecode.com/files/horn.ogg', 	URLsonF2vol : 100,URLsonF2ST:1,	
	KsFunSoundGun : false,soundURLF3 : 'https://koc-power-pdx.googlecode.com/files/gunshot.ogg', 	URLsonF3vol : 100,URLsonF3ST:1,
	reportScanner: {start:false, pages:5, pause:2, lastmsg:0}, inventory: {active:false, item:0},
	WWclick: false,GESeverytenmin:0,GESeveryhour:0,GESeveryday:0,pbAntiCheat: false,
	poptab_dismiss_tr:2, poptab_queue_tr: 1, tabmovementopen: false,
	speed1:true, speed2:true, speed3:true, speed4:true, speed5:true, speed6:true, speed7:true, speed8:true, speed10:true,
	dashboardX:0, dashboardY:0, RefreshSeed: false, RefreshSeedInterval: 45,
};
var Colors ={ChatLeaders:'#C8C8C8',ChatVC:'#81EE81',ChatChancy:'#F8A151',ChatAtt:'#FF7D7D',ChatAttFont:'#000',ChatWildAtt:'#526F35',ChatWildAttFont:'#000',ChatLowFood:'#6FDB5A',ChatLowFoodFont:'#000',ChatEcl:'#FFDD7D',ChatEclFont:'#000',ChatGlo:'#F9AAAA',ChatGloFont:'#141516',ChatAlliance:'#27D4F0',ChatAllianceFont:'#141516', BGImageURL: 'http://koc-power-pdx.googlecode.com/svn/trunk/img/kocpowerscbg.gif', 
userBG1 : "#333333",	userBG2 : "#584631",	userBG3 : "#FF0000",	userBG4 : "#CCCCFF",	userBG5 : "#CCCCFF",	userBG6 : "#CCCCFF",	userBG7 : "#CCCCFF",	userBG8 : "#CCCCFF",	userBG9 : "#CCCCFF",	userBG10 : "#CCCCFF",	userBG11 : "#333333",	userBG12 : "#584631",	userBG13 : "#FF0000",	userBG14 : "#CCCCFF",	userBG15 : "#CCCCFF",	userBG16 : "#CCCCFF",	userBG17 : "#CCCCFF",	userBG18 : "#CCCCFF",	userBG19 : "#CCCCFF",	userBG20 : "#CCCCFF",	userBG21 : "#333333",	userBG22 : "#584631",	userBG23 : "#FF0000",	userBG24 : "#CCCCFF",	userBG25 : "#CCCCFF",	userBG26 : "#CCCCFF",	userBG27 : "#CCCCFF",	userBG28 : "#CCCCFF",	userBG29 : "#CCCCFF",	userBG30 : "#CCCCFF",
MainTitle:'#FFFFFF', MainTitleHover:'#FF0000',MainTitleBackground: '#600000',MainTitle2:'#FFFFFF',MainTitle2Hover:'#FF0000', MainTitle2Background:'#600000'};
var AttackOptions={LastReport:0,MsgEnabled:true,MsgInterval:60,Method:"distance",SendInterval:8,MaxDistance:150,RallyClip:0,Running:false,BarbsFailedKnight:0,BarbsFailedRP:0,BarbsFailedTraffic:0,BarbsFailedVaria:0,BarbsFailedMarais:0,BarbsFailedBog:0,BarbsTried:0,DeleteMsg:true,DeleteMsgs0:false,Foodstatus:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},MsgLevel:{1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true,9:true,10:true},BarbsDone:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},BarbNumber:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},Levels:{1:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},2:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},3:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},4:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},5:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},6:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},7:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},8:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false}},Troops:{1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0}},MinDistance:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0},Distance:{1:750,2:750,3:750,4:750,5:750,6:750,7:750,8:750,9:750,10:750},Update:{1:[0,0],2:[0,0],3:[0,0],4:[0,0],5:[0,0],6:[0,0],7:[0,0],8:[0,0]},UpdateEnabled:true,UpdateInterval:30,stopsearch:1,knightselector:0}
var GlobalOptions={customWideScreenSize:1337,updateChatNote:"updateTextImageLike",enableBrowserBG:false,backStyle:"backImg", bgCol: '#222222', bgImg: 'http://koc-power-pdx.googlecode.com/svn/trunk/img/kocpowerscbg.gif', pbWatchdog:false,pbNoMoreKabam:false,pbWideScreen:true,pbWideScreenStyle:"wide",autoPublishGamePopups:false,autoPublishPrivacySetting : 80,escapeurl : null}
var ApothecaryOptions = {Active : false,goldkeep : 0,city : {0:[],1:[],2:[],3:[],4:[],5:[],6:[],7:[]},};
var CombatOptions={research:[{tch8:0,tch9:0,tch13:0,tch15:0},{tch8:0,tch9:0,tch13:0,tch15:0}],knt:[50,50],guardian:[["wood",0],["ore",0]],ratio:[{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}},{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}}]}
var CrestOptions = {
	Running   	: 	false,
	CrestCity 	: 	0,
	RoundOne  	: 	false,
	RoundTwo  	: 	true,
	lastRoundTwo 	: 	0,
	X				:	0,
	Y				:	0,
	R1ST			:	0,
	R1MM			:	0,
	R1Scout		:	0,
	R1Pike		:	0,
	R1Sword		:	0,
	R1Arch		:	0,
	R1LC			:	0,
	R1HC			:	0,
	R1SW			:	0,
	R1Ball		:	0,
	R1Ram			:	0,
	R1Cat			:	0,
	R1BT			:	0,
	R1EX			:	0,
	R1SWa			:	0,
	R2ST			:	0,
	R2MM			:	0,
	R2Scout		:	0,
	R2Pike		:	0,
	R2Sword		:	0,
	R2Arch		:	0,
	R2LC			:	0,
	R2HC			:	0,
	R2SW			:	0,
	R2Ball		:	0,
	R2Ram			:	0,
	R2Cat			:	0,
	R2BT			:	0,
	R2EX			:	0,
	R2SWa			:	0,
};
var CrestData = new Array();
function CrestFunc (Arr) {
	if (Arr == undefined)
		Arr = CrestOptions;

	this.Running 		=  	true;
	this.active 		=  	Arr.active;
	this.CrestCity 		= 	Arr.CrestCity;
	this.RoundOne 		= 	Arr.RoundOne;
	this.RoundTwo 		= 	true;
	this.lastRoundTwo 	= 	0;
	this.X 				= 	Arr.X;
	this.Y 				= 	Arr.Y;
	this.R1ST 			= 	Arr.R1ST;
	this.R1MM 			= 	Arr.R1MM;
	this.R1Scout 		= 	Arr.R1Scout;
	this.R1Pike 		= 	Arr.R1Pike;
	this.R1Sword 		= 	Arr.R1Sword;
	this.R1Arch 		= 	Arr.R1Arch;
	this.R1LC 			= 	Arr.R1LC;
	this.R1HC 			= 	Arr.R1HC;
	this.R1SW 			= 	Arr.R1SW;
	this.R1Ball 		= 	Arr.R1Ball;
	this.R1Ram 			= 	Arr.R1Ram;
	this.R1Cat 			= 	Arr.R1Cat;
	this.R1BT 			= 	Arr.R1BT;
	this.R1EX 			= 	Arr.R1EX;
	this.R1SWa 			= 	Arr.R1SWa;
	this.R2ST 			= 	Arr.R2ST;
	this.R2MM 			= 	Arr.R2MM;
	this.R2Scout 		= 	Arr.R2Scout;
	this.R2Pike 		= 	Arr.R2Pike;
	this.R2Sword 		= 	Arr.R2Sword;
	this.R2Arch 		= 	Arr.R2Arch;
	this.R2LC 			= 	Arr.R2LC;
	this.R2HC 			= 	Arr.R2HC;
	this.R2SW 			= 	Arr.R2SW;
	this.R2Ball 		= 	Arr.R2Ball;
	this.R2Ram 			= 	Arr.R2Ram;
	this.R2Cat 			= 	Arr.R2Cat;
	this.R2BT 			= 	Arr.R2BT;
	this.R2EX 			= 	Arr.R2EX;
	this.R2SWa 			= 	Arr.R2SWa;
};
var upgradeData = {  active : false, Items: [],  retryInterval : 30, };
var ThroneOptions = {
	Active:false,
	IntervalMin:3,
	Interval:30,
	RepairTime:0,
	Tries:0,
	minStones : 100000,
	Good:0,
	Bad:0,
	Items: [],
	delItem: 0,
	CityMax: false,
	i20001: false, //Rune des geringen Schutzes
	i20002: false, //Schutzrune
	i20003: false, //Rune der geringen Alchemie
	i20004: false, //Rune der Alchemie
	i20005: false, //Rune des geringen Gluecks
	i20006: false, //Gluecksrune
	i20019: false, //Super-Glückstoken
	i20022: false, //Lehrlings-Token
	i20012: false, //Meistertoken +3
	i20013: false, //Meistertoken +5
	i20014: false, //Meistertoken +7
	i20015: false, //Meistertoken +9
	i20016: false, //Meistertoken +10
	i20017: false, //Meistertoken +11
	i20018: false, //Meistertoken +12
	i20020: false, //Meistertoken +13
	i20021: false, //Meistertoken +14
	RepairAll: false,
	SalvageV2:{
		SaveXitems:0,
		QualityFilter:0,
		TypeFilter:{Advisor:true,Banner:true,Chair:true,Table:true,Window:true, Trophy:true, Candelabrum:true, Hero:true},
		EffectMode:0,EffectMode2:100,EffectMode3:100,
		EffectFilter:{},
		Preview:{ShowDel:true,ShowKeep:false},
		DeleteXitems:{IsEnabled:false,Value:3}, //v2.0.6b2
		LevelP1: false,
		CityMin: false,
	},
}; //EffectFilter:{}, // {Name:{IsEnabled,IsEnabled2,IsEnabled3,Percent},...}
var FarmOptions = {
	RallyClip: 0,
    Running: false,
    MinMight: 0,
    MaxMight: 999999999,
    Interval: 0,
    SendInterval: 10,
    MaxDistance: 20,
    Inactive:30,
	DeleteReports:false,
	Troops: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0,9: 0,10: 0,11: 0,12: 0},
	FarmNumber: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0},
    CityEnable: {1: true,2: true,3: true,4: true,5: true,6: true,7: true,8: true},
    CityLevel: {0: true,1: true,2: true,3: true,4: true,5: true,6: true,7: true,8: true,9: true,10: true,11: true,12: true},
    Diplomacy: {friendly: true,hostile: true,friendlyToThem: true,friendlyToYou: true,neutral:true,unallied:true},
    FarmMarches: [],
    farmMarches: {},
    Attacks:0,
	Checks:0,
};
var MarchOptions = { Queue: [] };
var MarchQueue = {1:[],2:[],3:[],4:[],5:[],6:[],7:[],8:[]};
var TabOptions = {
	toOverview : 10,
	toReports : 20,
	toMarches : 30,
	toSendMarch : 40,
	toTrain : 50,
	toAutoTrain : 60,
	toPopControl : 70,
	toThrone : 75,
	toThroneStuff : 80,
	toSearch : 90,
	toTurboSearch : 100,
	toPlayer : 110,
	toBuild : 120,
	toTransport : 130,
	toReassign : 140,
	toAutoCraft : 150,
	toFarm : 160,	
	toCrest : 170,
	toDarkForest : 180,
	toDarkForestOld : 190,
	toAttackTab : 200,
	toRaid : 210,
	toApothecary : 220,
	toScoutAlliance : 230,
	toWild : 240,
	toKnights : 250,
	toWildAttack : 260,
	toOptions : 270,
	toUserTab : 280,
	toKoCScripts : 290,
};
var KsRange = {
    rb    : 0,
    rdb   : 0,
    sb    : 0,
    sdb   : 0,
    rrb   : 0,
    rrdb  :	0,
    orb   :	0,
    ordb  :	0,
    osb   :	0,
    osdb  :	0,
    orrb  :	0,
    orrdb :	0,
};
var sacrifice = {
	1:[],
	2:[],
	3:[],
	4:[],
	5:[],
	6:[],
	7:[],
	8:[]
};

// EVAL PLUGINS
var avatars = {};
eval(GM_getResourceText("SYSTEM_AVATAR"));
var Smileys = {};
eval(GM_getResourceText("PLUGIN_SMILEYS")); 

// DOCUMENT STUFF
if (!releaseVersion) {
    var KsScriptRunning = ""+culang.optionsBeta+"";
    var KsScriptPage = "http://koc-power-all.webs.com/";
    var KsInstallLink = "http://mad-hatters-magic-elite.googlecode.com/svn/beta/bot.user.js";
    var KsLangpackFolder = "http://mad-hatters-magic-elite.googlecode.com/svn/beta/langpacks/";
    var  KsLatestVersion = ""+culang.optionsLatestInstall+" <a  href='http://mad-hatters-magic-elite.googlecode.com/svn/release/bot.user.js'  target='_blank'  title='"+culang.optionsLatestReleaseInstallNote+"'>"+culang.optionsRelease+"</a>  "+culang.mainVersion+" <a  href='http://mad-hatters-magic-elite.googlecode.com/svn/release/bot.user.js'  target='_blank'  title='"+culang.optionsLatestReleaseInstallNote2+"'>"+culang.optionsLatestInstall2+"</a>";
} else {
    var KsScriptRunning = ""+culang.optionsRelease+"";
    var KsScriptPage = "http://koc-power-all.webs.com/";
    var KsInstallLink = "http://mad-hatters-magic-elite.googlecode.com/svn/release/bot.user.js";
    var KsLangpackFolder = "http://mad-hatters-magic-elite.googlecode.com/svn/beta/"+KsLangpackFolderId+"/langpacks/";
    var  KsLatestVersion = ""+culang.optionsLatestInstall+" <a  href='http://mad-hatters-magic-elite.googlecode.com/svn/beta/bot.user.js'  target='_blank'  title='"+culang.optionsLatestBetaInstallNote+"'>"+culang.optionsBeta+"</a>  "+culang.mainVersion+" <a  href='http://mad-hatters-magic-elite.googlecode.com/svn/release/bot.user.js'  target='_blank'  title='"+culang.optionsLatestBetaInstallNote2+"'>"+culang.optionsLatestInstall2+"</a>";
}
readOptions();
function $(ID,root) {return (root||document).getElementById(ID);}

var bypassMulti = {
  MultiBrowserBypass : null,

  init : function (){
      t = bypassMulti;
      //t.MultiBrowserBypass = new CalterUwFunc ('update_seed_ajax', [[/if\s*\(typeof\s*isCancelTraining/im,'var l_lastCallTime = 0; var reload_requests = 0; var l_callIntervalMin = 10; if(typeof isCancelTraining'],[/if\s*\(rslt\.error_code\s*==\s*60\)/im,'return; if(rslt.error_code == 60)']]);
      t.MultiBrowserBypass = new CalterUwFunc ('update_seed_ajax', [[/if\s*\(typeof\s*isCancelTraining/im,'var l_lastCallTime = cm.l_lastCallTime; var reload_requests = cm.reload_requests; var l_callIntervalMin = cm.l_callIntervalMin; if(typeof isCancelTraining'],[/if\s*\(rslt\.error_code\s*==\s*60\)/im,'return; if(rslt.error_code == 60)']]);
      t.MultiBrowserBypass.setEnable(Options.MultiBrowser);
  },

  setEnable : function (tf){
	var t = bypassMulti;
	t.MultiBrowserBypass.setEnable (tf);
  },

  isAvailable : function (){
	var t = bypassMulti;
	return t.MultiBrowserBypass.isAvailable();
  },

}




var nHtml={FindByXPath:function(a,b,c){if(!c){c=XPathResult.FIRST_ORDERED_NODE_TYPE}try{var d=document.evaluate(b,a,null,c,null)}catch(e){GM_log("bad xpath:"+b)}if(c==XPathResult.FIRST_ORDERED_NODE_TYPE){if(d&&d.singleNodeValue){return d.singleNodeValue}}else{if(d){return d}}return null},ClickWin:function(a,b,c){var d=a.document.createEvent("MouseEvents");d.initMouseEvent(c,true,true,a,0,0,0,0,0,false,false,false,false,0,null);return!b.dispatchEvent(d)},Click:function(a){return this.ClickWin(window,a,"click")},ClickTimeout:function(a,b){window.setTimeout(function(){return nHtml.ClickWin(window,a,"click")},b+Math.floor(Math.random()*500))},SetSelect:function(a,b){for(var c=0;c<a.options.length;c++){if(b==a.options[c].value){a.options[c].selected=true;return true}}return false}}
if (document.URL.search(/kingdomsofcamelot.com\/fb\/e2\/src\/helpFriend_src.php/i) >= 0){ helpFriends (); return true;} //TODO Warnung: [KoCPower-Multilang@PDX] "return" aus dem Haupt-Scope wird normalerweise nicht unterstuetzt. Sie sollten dies im Benutzerskript beheben.
function helpFriends(){function a(){var b=ById("claimhelpform");if(!b){setTimeout(a,1e3)}b.submit()}a()}
//Kabams new cheat detector
uW.arthurCheck = function (a) {
  var b = false;
  for (var c = 0; c < a.length; c++) {
    if ($(unescape(a[c]))) {
      b = true;
      break
    }
  }
  if (b) {
    uW.AjaxCall.gPostRequest("ajax/funnelTracking.php", {
      action: 1300,
      serverId: uW.g_server,
      uid: uW.moderators[Math.floor((Math.random()*uW.moderators.length))]
    })
  }
};

readGlobalOptions();
if (document.URL.search(/apps.facebook.com\/kingdomsofcamelot/i) >= 0){
	setTimeout(function() {
		var test=document.URL;
		var testt = /s=([0-9]+)/i.exec(test);
		if (testt) {
			uW.window.document.title=""+ScriptName+" "+Version+" - ("+testt[1]+")";
		}
	}, 10000)
	facebookInstance ();
	return;
}
if (document.URL.search(/kingdoms-of-camelot\/play/i) >= 0){ kabamStandAlone(); return;}
// if (document.URL.search(/kabam.com\/games\/kingdoms-of-camelot\/play/i) >= 0){kabamStandAlone ();return;}
// if (document.URL.search(/kabam.com\/nl\/games\/kingdoms-of-camelot\/play/i) >= 0){kabamStandAlone ();return;}

if (document.URL.search(/facebook.com/i) >= 0){ if(document.URL.search(/connect\/uiserver.php/i) >= 0 || document.URL.search(/serverfbml/i) >= 0 || document.URL.search(/dialog\/stream.publish/i) >= 0 || document.URL.search(/dialog\/apprequests/i) >= 0 || document.URL.search(/dialog\/feed/i) >= 0) HandlePublishPopup ();return;}
if (document.URL.search(/kingdomsofcamelot.com/i) >= 0){kocWideScreen ();}

// FUNCTION
function readGlobalOptions (){
	s = GM_getValue ('KsOptions_??');
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts)
			GlobalOptions[k] = opts[k];
	}
}

function kocWideScreen(){
	var fois=0;
	function setWideFb(){var kocFrame=parent.document.getElementById('kocIframes1');
	if(!kocFrame){setTimeout(setWideFb,1000);return;}kocFrame.style.width='100%';
	if (ById("promo-sidebar")) ById("promo-sidebar").parentNode.removeChild(ById("promo-sidebar"));
	if (ById("sidebar_container")) ById("sidebar_container").parentNode.removeChild(ById("sidebar_container"));

	var style=document.createElement('style');style.innerHTML='body {margin:0; width:100%; !important;}';kocFrame.parentNode.appendChild(style);}
	function test(){var alla=ById('kocinitloading');if(alla){if(alla.style.display!="none"){fois++;if(fois>23)reloadKOC();setTimeout(test,2500);return}}}if(document.URL.match(/standalone=0/i)){test()}kocWatchdog();if(GlobalOptions.pbWideScreen)setWideFb();
}
	
function kabamStandAlone  (){
  if (ById("game_container")) ById("game_container").style.width="100%";
  if (ById("content")) ById("content").style.top="0px";
	function setWide (){
		var iFrames = ById('game_frame');
		if (!iFrames){
			setTimeout (setWide, 1000);
			return;
		}
		iFrames.style.width = '100%';
		while ( (iFrames=iFrames.parentNode) != null)
			if (iFrames.tagName=='DIV')
				iFrames.style.width = '100%';
		ById("main-nav").parentNode.removeChild(ById("main-nav"));
		ById("main-header").parentNode.removeChild(ById("main-header"));
try {
		ById("sidebar_container").style.display = "none";
} catch (e) {}	
		setTimeout(function() {if(ById("eu_privacy"))ById("eu_privacy").parentNode.removeChild(ById("eu_privacy"));},2000);
try {
		if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backCol") ById("content" && "gameIframe").style.backgroundColor= GlobalOptions.bgCol;
} catch (e) {}
try {
		if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backImg")  ById("content" && "gameIframe").style.backgroundImage = "url('"+GlobalOptions.bgImg+"')";
} catch (e) {}
	}
  function sendmeaway (){
	var serverID = /s=([0-9]+)/im.exec (document.location.href);
	var sr = /value="(.*?)"/im.exec ($("post_form").innerHTML);
	var goto = $("post_form").action+(serverID?"?s="+serverID[1]:'');
	var t = '<FORM target="_top" action="'+ goto +'" method=post><INPUT id=xxxpbutExplode type=submit value=RELOAD><INPUT type=hidden name=signed_request value="'+ sr[1] +'" /><INPUT type=hidden name=platform_req value=A /></form>';
	var e = document.createElement ('div');
	e.innerHTML = t;
	document.body.appendChild (e);
	setTimeout (function (){document.getElementById('xxxpbutExplode').click();}, 0);
  }
	if (GlobalOptions.pbWideScreen)
		setWide();
	if(GlobalOptions.pbNoMoreKabam)
		sendmeaway();

}
function facebookInstance(){function a(){var b=ById("iframe_canvas");if(!b){setTimeout(a,1e3);return}b.style.width="100%";while((b=b.parentNode)!=null)if(b.tagName=="DIV")b.style.width="100%";ById("globalContainer").style.left="0px";try{ById("rightCol").parentNode.removeChild(ById("rightCol"));ById("leftColContainer").parentNode.removeChild(ById("leftColContainer"))}catch(c){}
	var c=ById("mainContainer");if(c){if(GlobalOptions.pbWideScreenStyle=="normal")c.parentNode.style.minWidth="100%";var pied = ById('pagelet_canvas_footer_content');if(pied) { pied.parentNode.removeChild(pied); }if(GlobalOptions.pbWideScreenStyle=="wide")c.parentNode.style.width="1520px";if(GlobalOptions.pbWideScreenStyle=="ultra")c.parentNode.style.width="2000px";if(GlobalOptions.pbWideScreenStyle=="custom"){c.parentNode.style.width=GlobalOptions.customWideScreenSize+"px"; }for(i=0;i<c.childNodes.length;i++){if(c.childNodes[i].id=="contentCol"){c.childNodes[i].style.margin="0px";c.childNodes[i].style.paddingTop="0px";if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backCol") c.childNodes[i].style.backgroundColor= GlobalOptions.bgCol;if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backImg")  c.childNodes[i].style.backgroundImage = "url('"+GlobalOptions.bgImg+"')";break;}}}var c=ById("pageHead");if(c){c.style.width="80%";c.style.margin="0 10%"}var c=ById("bottomContent");if(c){c.style.padding="0px 0px 12px 0px"}}facebookWatchdog();if(GlobalOptions.pbWideScreen)a()}
function HandlePublishPopup() {
	if(GlobalOptions.autoPublishGamePopups){
		var FBInputForm = document.getElementById('uiserver_form');
		if(FBInputForm){
			var channel_input = nHtml.FindByXPath(FBInputForm,".//input[contains(@name,'channel')]");
			if(channel_input){
				var current_channel_url = channel_input.value;
				if (current_channel_url.match(/(http|https):\/\/(.*?)\.kingdomsofcamelot\.com(.*?)/i)) {
					var publish_label = document.getElementById('publish');
					var publish_button = nHtml.FindByXPath(publish_label,".//input[@type='submit']");
					var privacy_setting = nHtml.FindByXPath(FBInputForm,".//select[@name='audience[0][value]']");
					if(publish_button && privacy_setting){
						privacy_setting.innerHTML = '<option value="'+ GlobalOptions.autoPublishPrivacySetting +'"></option>';
						privacy_setting.selectedIndex = 0;
						nHtml.Click(publish_button);
					}
				}
			}
		}
		setTimeout(HandlePublishPopup, 1000);
	}
}
function facebookWatchdog(){function b(){try{if(ById("app_content_130402594779")==null){logit("KABAM SUFFERING FROM PEBKAC KOC NOT FOUND!");KOCnotFound(5*60)}}catch(a){logit("KABAM SUFFERING FROM PEBKAC KOC NOT FOUND!");KOCnotFound(4*60)}}var a=5e4;if(!GlobalOptions.pbWatchdog)return;setTimeout(b,a)}
function kocWatchdog(){function b(){if(ById("mod_maparea")==null && ById("click")==null){logit("ANOTHER KABAM PEBKAC ASLEEP ON JOB AND KoC not loaded");KOCnotFound(20)}}var a=1e4;if(!GlobalOptions.pbWatchdog)return;setTimeout(b,a)}

readOptions();
										        
// EMH SCRIPT STARTUP
function pdxStartup (){
	clearTimeout (KsStartupTimer);
	Seed = uW.seed;
	if (uW.KsLoaded)
		return;
	var metc = getClientCoords(ById('main_engagement_tabs'));
	if (metc.width==null || metc.width==0){
		KsStartupTimer = setTimeout (pdxStartup, 1000);
		return;
	}
	Seed = uW.seed;
	uW.KsLoaded = Version;
	readOptions();readColors();readTabOptions();//readLanguage();

	var showKsInfoBox = '.pdxInfoBox { background-image:url('+IMGksBG+'); font-variant:small-caps; padding: 8px; border-radius: 5px;  -moz-box-shadow: 0 0 2px 2px #141516; color: #FFFFFF;  max-height: 160px; width: 300px; margin-top:5px; } .pdxInfoBox a {color:#FFF; top:-2px; transition-duration: 0.2s; -moz-transition-duration: 0.2s; -webkit-transition-duration: 0.2s; -o-transition-duration: 0.2s;} .pdxInfoBox a:hover { color: #FF0000; margin-left: 2px;  box-shadow: 1px 1px 2px 0px #FF0000; padding: 0px 3px 0px 3px; }';
	var showMightKoCBugFix  = '';
	if (Options.showMightKoCBugFix) var showMightKoCBugFix = '#mainbody div#kochead.kocHeader div.taskbar div.rightColumn div.avatarInfo div.avatarStats div.avatarGlory { margin-left:30px; } .kocHeader .avatarStats .avatarLevel { padding-top:1px; left: -2px;  top: 35px;} .kocHeader .avatarMight, .kocHeader .avatarGlory {padding-left:1px;}';
	var showResKoCBugFix  = '';
	// if (Options.showResKoCBugFix) var showResKoCBugFix = '.kocmain .mod_cityinfo #cityinfo_1 table .grw {left: 650px;    margin-top: 25px;    position: fixed;    text-align: right;    width: 60px;} .kocmain .mod_cityinfo #cityinfo_1 table tbody tr td {    background-color: transparent;    border-bottom: 1px solid transparent;}';


	GM_addStyle ('.xtab {padding-right: 5px; border:none; background:none; white-space:nowrap;}\
	.tournamentTable { padding: 10px; border-radius:5px; border: 1px outset #141516; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px #eee; }\
	.'+culang.kocHostile+' td { background:crimson; }.'+culang.kocFriendly+' td{background:lightblue; }.'+culang.kocAllys+' td{background:royalblue; }\
	.'+culang.kocNeutral+' td { background:lightgreen; }.'+culang.kocNoAlliance+' td { background:gold; }\
	.xtabBR {padding-right: 5px; border:none; background:none;}\
	.buttonHelp {padding:1px; height:15px;font-size:9px;font-weight:bold; background-color:green;border-radius:5px; border: 1px outset #141516; }\
	.buttonHelp:hover {background-color:gray;}\
	div.ptDiv {background-color:none;}\
	table.pdxTab tr td {border:none; background:none; white-space:nowrap;}\
	table.ptTabPad tr td {border:none; background:none; white-space:nowrap; padding: 2px 4px 2px 8px;}\
	table.ptTabBR tr td {border:none; background:none;}\
	table.ksTabLined tr td {border:1px none none solid none; padding: 2px 5px; white-space:nowrap;}\
	table.ptTabPad tr td.pdxEntry {background-color:#ffeecc; padding-left: 8px;}\
	table.pdxTabOverview tr td {border-left:1px solid #ccc; white-space:nowrap; padding: 1px;   font-size:11px;}\
	table.ptNoPad tr td {border:none; background:none; white-space:nowrap; padding:0px}\
	.ptOddrow {background-color:#eee}\
	.pdxStatOverview {border: 0.5px inset #ffffff; border-radius:5px; -moz-box-shadow: inset 0px 0px 2px #ffffff; font-weight:bold; font-size:12px; font-variant:small-caps;   padding:3px; text-align:center; color:'+Colors.MainTitle+';	background-color:'+Colors.MainTitleBackground+';}\
	.pdxStat {border: 1px inset #ffffff; border-radius:3px 3px 3px 3px; -moz-box-shadow: 2px 2px 2px 2px #EEEEEE; font-weight:bold; font-size:14px; font-variant:small-caps;  padding:0px 10px; text-align:center; color:'+Colors.MainTitle+';	background-color:'+Colors.MainTitleBackground+'; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
	.pdxStat a { font-weight:bold; font-size:14px; color:'+Colors.MainTitle+';  font-variant:small-caps;  text-decoration: none; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
	.pdxStat a:hover { font-size:15px; color:'+Colors.MainTitleHover+'; text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; }\
	.pdxStat2 {border: 0.5px inset #ffffff;  border-radius:3px 3px 3px 3px; -moz-box-shadow: 2px 2px 2px 2px #EEEEEE; font-weight:bold; font-size:11px; font-variant:small-caps;  padding:0px 10px; text-align:center; color:'+Colors.MainTitle2+';	background-color:'+Colors.MainTitle2Background+'; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
	.pdxStat2 a { font-weight:bold; font-size:11px; color:'+Colors.MainTitle2+';  font-variant:small-caps;  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000;  text-decoration: none; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
	.pdxStat2 a:hover { font-size:12px; color:'+Colors.MainTitle2Hover+';  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; }\
    .pbStatRed {border:1px solid; border-color:#000000; font-weight:bold; padding-top:2px; padding-bottom:2px; text-align:center; color:#ffffff ; background-color:red;  border-radius:5px;}\
	.pdxEntry {padding: 7px; border:1px solid; border-color:#000000; background-color:#ffeecc; white-space:nowrap;}\
	.ptErrText {font-weight:bold; color:#600000}\
	.pdxStatLight {font-weight:bold;  font-variant:small-caps;  padding:0px 10px; text-align:center; color:'+Colors.MainTitle+';	 -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
	.pdxStatLight a {font-weight:bold;  color:'+Colors.MainTitle+';  font-variant:small-caps;  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000;  text-decoration: none; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
	.pdxStatLight a:hover { font-size:11px; color:'+Colors.MainTitleHover+'; text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; }\
	button::-moz-focus-inner, input[type="submit"]::-moz-focus-inner { color:#FFFFFF; border: none; border-radius:5px; }\
	input[type="text"] { padding: 1px; border: 0.5px inset #141516;   }\
	input[type="button"],input[type="submit"] { border: 1px outset #141516;  border-radius:3px; }\
	input[type="submit"]:hover,input[type="button"]:hover  { color: #600000; background-color:#FFFFFF; }\
	.ptChatWhisper {}\
	.ptChatLowFood {color: '+Colors.ChatLowFoodFont+'; font-weight:bold; background-color: '+Colors.ChatLowFood+'; }\
	.ptChatWildAttack {color: '+Colors.ChatWildAttFont+'; font-weight:bold; background-color: '+Colors.ChatWildAtt+'; }\
	.ptChatAttack {color: '+Colors.ChatAttFont+'; font-weight:bold; background-color: '+Colors.ChatAtt+'; }\
	.ptChatScout {color: '+Colors.ChatEclFont+'; font-weight:bold; background-color: '+Colors.ChatEcl+'; }\
	.ptChatAlliance {}\
	.ptChatGlobal {background-color: #fdd}\
	.ptChatIcon {border: 1px inset red; border-radius:3px;}\
	.ptChatScripter {font-weight:bold;}\
	.ptChatCHAN {color:#000; background-color:'+Colors.ChatChancy+';}\
	.ptChatVICE {color:#000; background-color:'+Colors.ChatVC+';}\
	.ptChatOFFI {color:#000; background-color:'+Colors.ChatLeaders+';}\
	input.defButtonOn { cursor:pointer; border:1px solid black; background-color:red;}\
	input.defButtonOff { cursor:pointer; border:1px solid black; background-color:#0a0;}\
	span.whiteOnRed {padding-left:3px; padding-right:3px; background-color:#700; color:white; font-weight:bold}\
	span.boldRed {color:#800; font-weight:bold}\
	span.boldDarkRed {color:#600; font-weight:bold}\
	span.boldGreen {color:green; font-weight:bold}\
	span.helpText {color:#555555; font-style:italic; font-size:9px;}\
	span.helpTextImp {color:#600000; font-style:italic; font-size:11px;}\
	span.shadowCaps {color:#0000; font-weight:bold;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps; text-align:center}\
	span.logTime {font-size: 9px; color:#141516; text-align:center}\
	span.shadowCapsItalic {color:#0000; font-style:italic;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps; text-align:center}\
	.emoicon {width:19px !important;height:19px !important;float:none !important;}\
	.castleBut {outline:0px; margin-left:0px; margin-right:0px; width:24px; height:26px; font-size:12px; font-weight:bold;}\
	.castleBut:hover {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
	.castleButNon {background-image:url("'+ URL_CASTLE_BUT +'")}\
	.castleButSel {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
	a.ptButton20 {color:#ffff80}\
	input.ksMSubtab {cursor:pointer; width:10em; margin-right:15px;}\
	input.ksMSubtabSel {background-color:#444444; color:white; font-weight:bold; cursor:none !important}\
	input.ptButCancel { background-color:#a00; font-weight:bold; color:#fff}\
	multiTab {}\
	table.mulltiMainTabs { empty-cells: show;  margin-left: 5px;  margin-top: 4px; padding: 1px; }\
	.ksTabSel {  font-weight:bold; font-variant:small-caps; color : #2F230E; white-space: nowrap; cursur:pointer; height: 17px;   }\
	.ksTabSel span {  color : #2F230E; background: url("'+IMGtabSelected+'"); display: inline-block; width: 78px;   height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
	.ksTabNotSel { font-weight:500;  font-variant:small-caps; color: #2F230E; white-space: nowrap; cursur:pointer; height: 17px; }\
	.ksTabNotSel span {  color : #2F230E; background: url("'+IMGtabNoSelect+'"); display: inline-block; width: 78px;  height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
	.ksTabSelLeft {  font-weight:bold; font-variant:small-caps; color : #2F230E; white-space: nowrap; cursur:pointer; height: 17px;   }\
	.ksTabSelLeft span {  color : #2F230E;  width: 78px;   height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
	.ksTabNotSelLeft { font-weight:500;  font-variant:small-caps; color: #2F230E; white-space: nowrap; cursur:pointer; height: 17px; }\
	.ksTabNotSelLeft span {  color : #2F230E;  width: 78px;  height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
	tr.ksCPopupTop td { border:none; height: 15px;  padding:0px; background:none;}\
	.Ksptretry_top { background-color:#a00; color:#fff; border:none; height: 21px; padding:0px; }\
	.popupBanner { margin-bottom:10px; height:25px; background-color:#600000; text-align:center;font-size: 20px; font-weight:bold; font-variant:small-caps; color:#FFFFFF; text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; border:1px inset #141516; border-radius:5px; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px #eee;}\
	.ksCPopup .ksCPopMain {  opacity:0.9;overflow:auto;border:none; background:none; }\
	.idp_CPopup .idp2_CPopup { opacity:0.9; }\
	#ksQuick.tabs_engagement span center b a {color:#FFFFFF;}\
	#ksQuick.tabs_engagement span center b a:hover {color:#FF0000;}\
	.hasTooltip {display: inline;position: relative;}\
	.hasTooltip span {display:none;}\
	#ksQuick.tabs_engagement a#pbOutgoingButton.tab{ background:none; }\
	#ksQuick.tabs_engagement a#pbIncomingButton.tab{ background:none; }\
	.hasTooltip:hover span {display:inline-block;z-index:99999;background-color:#FFFFE6;border-radius:5px;color:black;box-shadow:1px 1px 3px gray;position:absolute;padding:5px;top:25px;left:25px;}\
	.ptChatUser1 {background-color: '+ Colors.userBG1 +';}		.ptChatUser2 {background-color: '+ Colors.userBG2 +';}	.ptChatUser3 {background-color: '+ Colors.userBG3 +';}	.ptChatUser4 {background-color: '+ Colors.userBG4 +';}	.ptChatUser5 {background-color: '+ Colors.userBG5 +';}	.ptChatUser6 {background-color: '+ Colors.userBG6 +';}	.ptChatUser7 {background-color: '+ Colors.userBG7 +';}	.ptChatUser8 {background-color: '+ Colors.userBG8 +';}	.ptChatUser9 {background-color: '+ Colors.userBG9 +';}	.ptChatUser10 {background-color: '+ Colors.userBG10 +';}	.ptChatUser11 {background-color: '+ Colors.userBG11 +';}		.ptChatUser12 {background-color: '+ Colors.userBG12 +';}	.ptChatUser13 {background-color: '+ Colors.userBG13 +';}	.ptChatUser14 {background-color: '+ Colors.userBG14 +';}	.ptChatUser15 {background-color: '+ Colors.userBG15 +';}	.ptChatUser16 {background-color: '+ Colors.userBG16 +';}	.ptChatUser17 {background-color: '+ Colors.userBG17 +';}	.ptChatUser18 {background-color: '+ Colors.userBG18 +';}	.ptChatUser19 {background-color: '+ Colors.userBG19 +';}	.ptChatUser10 {background-color: '+ Colors.userBG20 +';}	.ptChatUser21 {background-color: '+ Colors.userBG21 +';}		.ptChatUser22 {background-color: '+ Colors.userBG22 +';}	.ptChatUser23 {background-color: '+ Colors.userBG23 +';}	.ptChatUser24 {background-color: '+ Colors.userBG24 +';}	.ptChatUser25 {background-color: '+ Colors.userBG25 +';}	.ptChatUser26 {background-color: '+ Colors.userBG26 +';}	.ptChatUser27 {background-color: '+ Colors.userBG27 +';}	.ptChatUser28 {background-color: '+ Colors.userBG28 +';}	.ptChatUser29 {background-color: '+ Colors.userBG29 +';}	.ptChatUser10 {background-color: '+ Colors.userBG30 +';}\
	'+showMightKoCBugFix+'\
	'+showResKoCBugFix+'\
	'+showKsInfoBox+'\
	');
	setCities();readTrainingOptions();readThroneOptions();readFarmOptions();readDFOptions();readAtkOptions();readCrestData();readMarchOptions();readDashboardOptions();readApothecaryOptions();readCombatOptions();readKsRange();
	CM.cheatDetector.detect = foo;
	if (Options.ptWinPos==null || Options.ptWinPos.x==null|| Options.ptWinPos.x=='' || isNaN(Options.ptWinPos.x)){
		var c = getClientCoords (ById('main_engagement_tabs'));
		Options.ptWinPos.x = c.x+4;
		Options.ptWinPos.y = c.y+c.height;
		saveOptions ();
	}
	if (Options.ptWin2Pos==null || Options.ptWin2Pos.x==null|| Options.ptWin2Pos.x=='' || isNaN(Options.ptWin2Pos.x)){
		var c = getClientCoords (ById('main_engagement_tabs'));
		Options.ptWin2Pos.x = c.x+4;
		Options.ptWin2Pos.y = c.y+c.height;
		saveOptions ();
	}
	if(!GlobalOptions.pbWideScreen && Options.ptWinPos.x > 700){
		var c = getClientCoords (ById('main_engagement_tabs'));
		Options.ptWinPos.x = c.x+4;
		saveOptions ();
	}
	var hauteur=parseIntNan(Options.HauteurBoite) + 30;
	mainPop = new CPopup ('idp1', Options.ptWinPos.x, Options.ptWinPos.y, 800, hauteur, Options.ptWinDrag,
		function (){
			tabManager.hideTab();
			Options.pbWinIsOpen=false;
			saveOptions()
		});
	var mainDiv = mainPop.getMainDiv();
	mainPop.getTopDiv().innerHTML = '<TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs></span></td></tr></table>';
	mainPop.autoWidth(true);
	
	AddMainTabLink("<IMG height='36' src='"+IMGbuttonPower+"' alt='POWER' title='KoC Power - Main Tabs'>", eventHideShow, mouseMainTab);
	var outgoingButton = "";
	var incomingButton = "";
	var infoButton = "";
	AddSubTabLink('<img src='+infoButton+'>', QueueMarches.init, 'pbOutgoingButton', "none");
	AddSubTabLink('<img src='+outgoingButton+'>', OutgoingMarches.init, 'pbOutgoingButton', "none");
	AddSubTabLink('<img src='+incomingButton+'>', IncomingMarches.init, 'pbIncomingButton', "none");
	AddSubTabLink('<span style="color:yellow;">'+culang.tabLabelMovement+'</span>', Movement.init, 'pbMovementButton', "blue");
	document.getElementById('pbIncomingButton').style.display = "none";
	tabManager.init (mainPop.getMainDiv());
	TowerAlerts.init();
	AllianceReports.init ();
	DispReport.init();
	messageNav.init();
	RefreshEvery.init();
	Dashboard.init();
	ChatStuff.init ();
	battleReports.init ();
	AttackDialog.init();
	ChatPane.init();
	CoordBox.init();
	bypassMulti.init();
	Tabs.Rpt.AutoStart();
	
	if (!ThroneOptions.Active) {
		setTimeout(function() { RepairAuto.init (); },15000);
	} else {
		Options.salvageconfig.Repairrunning=false;
	}
  setInterval(eachSecond,1000);
  // if (firefoxVersion.substring(0,4) >=16){
  	// uW.jQuery("#hudAvatarPic").attr("class", "");
  	// document.getElementById('hudAvatarPic').innerHTML = '<img src="https://graph.facebook.com/'+ uW.user_id +'/picture">';
  	// document.getElementById('hudAvatarPic').onclick = null;
  // }
	setTimeout(function() {
		DeleteReports.init();
		// exportToKOCattackKs.init();
		SpamEvery.init ();
		SpamEveryA.init ();
		CollectGold.init();
		FairieKiller.init (Options.pbKillFairie);
		FoodAlerts.init();
	},60000); // on attends 60 sec avant le lancement de certains fonction
	if (Options.pbWinIsOpen){
		mainPop.show (true);
		tabManager.showTab();
	}

	window.addEventListener('unload', onUnload, false);
	TowerAlerts.setPostToChatOptions(Options.alertConfig);
	
	AddMainTabLink2("<IMG height='36' src='"+IMGbuttonQuick+"'  alt='QUICK' title='KoC Power - Quick Tabs'>", eventHideShow2, mouseMainTab2);
	WideScreen.init ();
	WideScreen.setChatOnRight (Options.pbChatOnRight);
	WideScreen.useWideMap (Options.pbWideMap);
	gmtClock.init();
	demist();

	var params = uW.Object.clone(uW.g_ajaxparams);
	params.format = 2;
	params.tournyPos = 0;
	new AjaxRequest(uW.g_ajaxpath + "ajax/getLeaderboard.php" + uW.g_ajaxsuffix, {
		method: "post",
		parameters: params,
		onSuccess: function (transport) {
			var rslt = eval("(" + transport.responseText + ")");
			if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
			if (rslt.ok) {
				if (rslt.data) {
					ById("pdxTabs2").innerHTML = '<IMG alt="' + culang.mainTournament + '" height="36" src="' + IMGbuttonQuickTournament + '" title="' + culang.mainTournament + '">';
				}
			}
		}
	})
	
	if (Options.currentTab2) {
		currentName2 = Options.currentTab2;
		if (currentName2=='Overview1')  currentName2 = 'Production';
		if (currentName2=='map')  currentName2 = 'Production';
		if (currentName2=='build')  currentName2 = 'Production';
		if (currentName2=='AutoTrain') currentName2 = 'Production';
		if (currentName2=='Throne') currentName2 = 'Production';
		if (currentName2=='Movement') currentName2 = 'Production';
	} else {
		currentName2 = 'Production';
	}

	mainPop2 = new CPopup ('idp2', Options.ptWin2Pos.x, Options.ptWin2Pos.y, 779,350, true,
		function (){
			if (Tabs2[currentName2]==undefined) {
				currentName2 = 'Production';
			}
			Tabs2[currentName2].hide();
			Options.ptWin2IsOpen=false;
			saveOptions();
		});

	var mainDiv2 = mainPop2.getMainDiv();

	if (Options.pdxMenuLeft) {
		mainPop2.getTopDiv().innerHTML = '<div class=pdxMenu style="display:'+Options["powerMenuOptions"]+';position:fixed; margin-left:-126px;margin-top:-36px; padding:2px; border: 1px outset #141516; border-radius:'+Options.popupBorderRadius+'; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee; box-shadow: 2px 2px 2px 2px #eee;"><TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs2></span></td></tr></table></div>';
	} else {
		mainPop2.getTopDiv().innerHTML = '<TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs2></span></td></tr><tr><td><span id=idTabs3></span></tr></table>';
	}

	mainPop2.autoHeight (true);
	mainPop2.autoWidth(true);

	var eTabs2 = ById('idTabs2');

	for (k=0; k<Tabs2.length; k++){
		var a=document.createElement('a');

		a.id = 'ab'+ Tabs2[k][0];
		if (Options.pdxMenuLeft) {
			a.innerHTML='<span id="spp'+ Tabs2[k][0] +'" class="multiTab">'+ Tabs2[k][1] +'</span><BR>';
		} else {
			a.innerHTML='<span id="spp'+ Tabs2[k][0] +'" class="multiTab">'+ Tabs2[k][1] +'</span>';

			if (k==9) {
				var eTabs2 = ById('idTabs3');
				eTabs2.innerHTML+="</tr><tr><td>";
			}
		}
		eTabs2.appendChild(a);
		a.addEventListener('click', clickedTab2, false);
		Tabs2[Tabs2[k][0]].init();
		cont = Tabs2[Tabs2[k][0]].getContent();
		if (Tabs2[k][0]==currentName2) {
			cont.style.display = 'block';
			if (Options.pdxMenuLeft) {  a.className='ksTabSelLeft'; } else { a.className='ksTabSel'; }
		}else {
			cont.style.display = 'none';
			if (Options.pdxMenuLeft) {   a.className='ksTabNotSelLeft'; } else {  a.className='ksTabNotSel'; }
		}
		mainDiv2.appendChild(cont);
	}

	if (Options.ptWin2IsOpen){
		mainPop2.show (true);
		if (Tabs2[currentName2]==undefined) {
			currentName2 = 'Production';
		}
		Tabs2[currentName2].show();
	}

	if (Options.SelQG) {
		if (parseIntNan(Options.alertConfig.hq)>0) {
			setTimeout(function() {
				var idx=Cities.byID[Options.alertConfig.hq].idx;
				try {
				uW.citysel_click(ById('citysel_'+ (idx+1)));
				} catch (ex) {}
			},1000);
		}
	}
	actionLog("Multi","<div style='font-weight:bold;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;'><a href='"+homePage+"' target='_blank'>"+ScriptName+"</a> "+culang.mainSuccessfullyLoaded+" <BR>"+culang.mainVersion+": <span class='boldRed'>"+Version+"</span> / "+culang.mainLangpackVersion+" <span class='boldRed'>"+LangpackVersion+"</span></div>");

	//Check, ob Bauauftrag fertig ist
	setInterval(Buildcheck, 750);
	//Merlin Fenster ausblenden
	if (Options.merlinClose && Seed.items.i599 && Seed.items.i599 > 0) setTimeout(closeMerlin, 500);
	//Werbebutton entfernen

	if (Options.deleteButtons) setInterval(deleteButtons, 5000);
	setInterval(checkmarches, 1000);
	setInterval(checkunits, 1000);
	if (Options.alertSound.alarmActive && Options.alertSound.expireTime>unixTime()) {
		setTimeout(Tabs.Options.soundTheAlert, 2500);
	}		
	setInterval(GlobalEachSecond,1000);//lets move everything under this one.
	uW.pop_treasure_chest_modal = treasure_chest_post;
	
}
//</editor-fold>

function treasure_chest_post(tid) {
	actionLog(culang.TreasureChest,culang.TreasureChestFound);
	if (Options.TresureChestFB) {
		var mid = tid;
		var params = uW.Object.clone(uW.g_ajaxparams);	
		params.tid = tid;
		new AjaxRequest(uW.g_ajaxpath + "ajax/postFriendVictoryTokenShare.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					var reparr = new Array();
					var city = '';
					for (c in Seed.queue_atkp) {
						if (Seed.queue_atkp[c]['m'+mid]) city = c;
					}
					var tileName = (Seed.queue_atkp[city]["m" + mid].toTileType == 51) ? "Barbarian Camp" : uW.g_mapObject.types[parseInt(Seed.queue_atkp[city]["m" + mid].toTileType)].capitalize();
					reparr.push(["REPLACE_CiTyId", city.substr(4)]);
					reparr.push(["REPLACE_CiTyNaMe", Cities.byID[city.substr(4)].name]);
					reparr.push(["REPLACE_TiLeNaMe", tileName]);
					reparr.push(["REPLACE_fEeDiD", rslt.feedId]);
					reparr.push(["REPLACE_tOkEnId", rslt.tokenId]);
					try {
					uW.common_postToProfile("118", reparr);
					} catch (ex) {
						actionLog(culang.TreasureChest,culang.TreasureChestNoFB);
					}
					actionLog(culang.TreasureChest,culang.TreasureChestFB);
				} else {
					actionLog(culang.TreasureChest,culang.TreasureChestErr1 +' '+ JSON.stingify(rslt));
				}
			},
			onFailure: function () {
				actionLog(culang.TreasureChest,culang.TreasureChestErr2);
			},
		});
	}
}

Seedcounter = 0;
function RefreshSeed(){
	actionLog("Seed","Refreshing Seed!");
	if (uW.g_update_seed_ajax_do == true) {
		Seedcounter++;
		if (Seedcounter < 3) {
			setTimeout(RefreshSeed, 2000);
			actionLog("Seed","Refreshing Seed! Break!");
			return;
		} else {
			Seedcounter = 0;
		}
	}
	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
	// stop update_seed_ajax
	uW.g_update_seed_ajax_do = true;
	RefreshingSeed = true;
	
  	
	var ts = (new Date().getTime() / 1000) + uW.g_timeoff;
    var cts = parseInt( (ts - 30) * 1000);
    var upd = window.self.location.href;
    upd=upd.replace(/ts=\d*\.\d+/, "ts="+ts);
    upd=upd.replace(/cts=\d*/, "cts="+cts);
	
	new AjaxRequest(upd, {
	    method: "POST",
	    parameters: params,
	    onSuccess: function (rslt) {
	      var mainSrcHTMLCode = rslt.responseText;
	    	var myregexp = /var seed=\{.*?\};/;
	    	var match = myregexp.exec(mainSrcHTMLCode);
	    	if (match != null) {
	    		result = match[0];
	    		result = result.substr(4);
	    		var seed = eval(result);
				
	    		if (seed.ss) unsafeWindow.seed.ss = seed.ss;
	    		if (seed.queue_atkinc) unsafeWindow.seed.queue_atkinc = seed.queue_atkinc;
	    		if (seed.players) unsafeWindow.seed.players = seed.players;
					if (seed.queue_sacr) unsafeWindow.seed.queue_sacr = seed.queue_sacr;
					
					//Throne erneuern
					if (seed.throne) unsafeWindow.seed.throne = seed.throne;
					if (seed.queue_throne) unsafeWindow.seed.queue_throne = seed.queue_throne;
					unsafeWindow.kocThroneItems = {};
					unsafeWindow.createThroneItems();
					unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
					unsafeWindow.cm.ThroneView.renderThrone();
					unsafeWindow.cm.ThroneView.renderStats();

					if (seed.items) unsafeWindow.seed.items = seed.items;
					if (seed.courtItems) unsafeWindow.seed.courtItems = seed.courtItems;

					if (seed.queue_atkp) unsafeWindow.seed.queue_atkp = seed.queue_atkp;
					
					if (seed.cityData) unsafeWindow.seed.cityData = seed.cityData;
					if (seed.cities) unsafeWindow.seed.cities = seed.cities;
					if (seed.citystats) unsafeWindow.seed.citystats = seed.citystats;
					if (seed.queue_craft) unsafeWindow.seed.queue_craft = seed.queue_craft;

					if (seed.knights) unsafeWindow.seed.knights = seed.knights;
					if (seed.units) unsafeWindow.seed.units = seed.units;
					if (seed.buildings) unsafeWindow.seed.buildings = seed.buildings;
					if (seed.queue_con) unsafeWindow.seed.queue_con = seed.queue_con;
					if (seed.updateHelpConstruct) unsafeWindow.seed.updateHelpConstruct = seed.updateHelpConstruct;
					if (seed.con_hlp) unsafeWindow.seed.con_hlp = seed.con_hlp;
					//if (seed.resources) unsafeWindow.seed.resources = seed.resources;

					if (seed.playerEffects) unsafeWindow.seed.playerEffects = seed.playerEffects;
					if (seed.tech) unsafeWindow.seed.tech = seed.tech;
					if (seed.quests) unsafeWindow.seed.quests = seed.quests;
					if (seed.guardian) unsafeWindow.seed.guardian = seed.guardian;
					if (seed.wildDef) unsafeWindow.seed.wildDef = seed.wildDef;
					if (seed.wilderness) unsafeWindow.seed.wilderness = seed.wilderness;
					if (seed.woundedUnits) unsafeWindow.seed.woundedUnits = seed.woundedUnits;
					if (seed.queue_revive) unsafeWindow.seed.queue_revive = seed.queue_revive;
					if (seed.queue_revive2) unsafeWindow.seed.queue_revive2 = seed.queue_revive2;
					if (seed.fortifications) unsafeWindow.seed.fortifications = seed.fortifications;
					if (seed.queue_fort) unsafeWindow.seed.queue_fort = seed.queue_fort;
					if (seed.leaders) unsafeWindow.seed.leaders = seed.leaders;
					if (seed.queue_unt) unsafeWindow.seed.queue_unt = seed.queue_unt;
					if (seed.tech2) unsafeWindow.seed.tech2 = seed.tech2;
					if (seed.queue_tch) unsafeWindow.seed.queue_tch = seed.queue_tch;
					if (seed.queue_tch2) unsafeWindow.seed.queue_tch2 = seed.queue_tch2;
					if (seed.updateHelpResearch) unsafeWindow.seed.updateHelpResearch = seed.updateHelpResearch;
					if (seed.tch_hlp) unsafeWindow.seed.tch_hlp = seed.tch_hlp;
					if (seed.updateHelpResearch2) unsafeWindow.seed.updateHelpResearch2 = seed.updateHelpResearch2;
					if (seed.tch_hlp2) unsafeWindow.seed.tch_hlp2 = seed.tch_hlp2;
					if (seed.queue_mkt) unsafeWindow.seed.queue_mkt = seed.queue_mkt;
					if (seed.allianceDiplomacies) unsafeWindow.seed.allianceDiplomacies = seed.allianceDiplomacies;
					if (seed.allianceNames) unsafeWindow.seed.allianceNames = seed.allianceNames;
					if (seed.newReportCount) unsafeWindow.seed.newReportCount = seed.newReportCount;
					if (seed.newDisasterReportCount) unsafeWindow.seed.newDisasterReportCount = seed.newDisasterReportCount;
					if (seed.newTradeReports) unsafeWindow.seed.newTradeReports = seed.newTradeReports;
					if (seed.newMailCount) unsafeWindow.seed.newMailCount = seed.newMailCount;
					if (seed.playerSettings) unsafeWindow.seed.playerSettings = seed.playerSettings;
					if (seed.loginReward) unsafeWindow.seed.loginReward = seed.loginReward;
					if (seed.player) unsafeWindow.seed.player = seed.player;
					if (seed.multiQueue) unsafeWindow.seed.multiQueue = seed.multiQueue;
					
	    		unsafeWindow.document.seed = unsafeWindow.seed;
	    		Seed = unsafeWindow.seed;
					actionLog("Seed","Refreshing Seed! Done!");
	    	}
				SecondLooper = 1;	
				// let update_seed_ajax run again
				uW.g_update_seed_ajax_do = false;
				RefreshingSeed = false;
	    },
	    onFailure: function () {
				SecondLooper = 1;	
				// let update_seed_ajax run again
				uW.g_update_seed_ajax_do = false;
				RefreshingSeed = false;
				actionLog("Seed","Refreshing Seed! Fail!");
	    },
	});
}

//<editor-fold desc="SPLIT:Tabs/Movement.js">
//	
//	   KOC POWER - TIMER												        
//	

var GESeachmin = 0;
var atwomin = 0;
var SecondLooper = 1;
var RefreshingSeed = false;
function GlobalEachSecond () {
	var unixtime = uW.unixtime();
  if(GESeachmin < unixtime) {
  	GESeachmin = Number(unixtime+60);
  	new GESeverymin(unixtime);
  };
	
	/* Automatically Refresh Marches in Seed, if Option set */  
	SecondLooper++;
	if (Options.RefreshSeed && ((SecondLooper % Options.RefreshSeedInterval) == 1)) {
		setTimeout(function() {RefreshSeed();},250);
	}
	
	//Fenster schließen lassen
	var x = ById('modalBox1');
	if (x) 
		if(String(x.innerHTML).indexOf("atk march no row change") > -1){
			uW.Modal.hideModal();
		}
		
};

function GESeverymin (unixtime) {//put functions here to execute every min
	if(atwomin == 0) atwomin = Number(unixtime+2*60);
	logit('a2min is '+atwomin);
	logit('unixtime is '+unixtime);
	if(atwomin < unixtime) {
		atwomin = Number(unixtime+2*60);
		new GESeverytwomin(unixtime);
	};
	if(Options.GESeverytenmin < unixtime) {
	  	Options.GESeverytenmin = Number(unixtime+10*60);
		saveOptions();
		new GESeverytenmin(unixtime);	
	};  
		//start window open in other browser warning auto click//cmModalContainer guardian_generic undefined cmModal1
		if(Options.WWclick) {
		//for (z =1;z<5;z++) {
			var x = document.getElementsByClassName('cmModalContainer guardian_generic undefined cmModal1');
			if(!x)
			var x = document.getElementsByClassName('cmModalContainer guardian_generic undefined cmModal2');
			if(!x)
			var x = document.getElementsByClassName('cmModalContainer guardian_generic undefined cmModal3');
			if(x)
				if(x.length > 0) {
					for(y = 0; y < x.length;y++) {
						if(String(x[y].innerHTML).indexOf("You have Kingdoms of Camelot open in a newer window. If you have multiple connections to the same world open, please use your most recent window for the best experience and close this one.") > -1){
							uW.cm.ModalManager.close();
						}
					};
				}
			//}
		};
	//end window open in other browser warning auto click
};

function GESeverytwomin (unixtime) {//put functions here to execute every 2 min
	new detafk();
	// new Tabs.Throne.rotatethrone();
};

function GESeverytenmin (unixtime) {//put functions here to execute every 10 min
  if(Options.GESeveryhour < unixtime){
  	Options.GESeveryhour = Number(unixtime+60*60);
	saveOptions();
	new GESeveryhour(unixtime);
  };
  // if(GiftDB.adgift) new Tabs.gifts.scangifts(4);
};

function GESeveryhour (unixtime) {//put functions here to execute every hour
  if(Options.GESeveryday < unixtime){
  	Options.GESeveryday = Number(unixtime+24*60*60);
	saveOptions();
	new GESeveryday(unixtime);
  };
	// if(Options.spamconfig.aspam )Tabs.Spam.Count();
	MAP_DELAY = Options.MAP_DELAY;
};

function GESeveryday (unixtime) {//put functions here to execute every day
  // if(GlobalOptions.pbupdate)AutoUpdater();//check for script updates
};

/************** End Timer **************/

/************** Afk detector **************/

var afk = 0;
var afkb=-1;
function afkwatcher () {
	document.body.onmousemove = function(){
		afk++
	};
	document.body.onkeypress = function(){
		afk++
	};
};
function detafk () {
	logit('afk '+afk);
	if (afk == afkb) {
		logit('afk detected');
		isAFK = true;
	} 
	else isAFK = false;
	afkb = afk;
}
/************** End Afk detector **************/
 //</editor-fold>
 

//<editor-fold desc="SPLIT:Tabs/Movement.js">
//	
//	   KOC POWER - TABS MOVEMENT										        
//	
uW.clickKoords = function(c) {
	var b = c.srcElement ? c.srcElement : c.target;
	var d = b.innerHTML.split(",");
	var a = d[0].substr(1);
	var f = d[1].substr(0, d[1].length - 1);
	if (Options.tabmovementopen) { 
		if (!Movement.active) Movement.init();
		ById('RAAtypetrpx').value = a;
		ById('RAAtypetrpy').value = f;
		Movement.rechercheDEST();
		Movement.estimerRes();
	}
	uW.cm.utils.CoordinateLinkController.onClick(c);
}

 
var paintMov = null;
Movement = {
	active: false,
	cont : null,
	displayTimer : null,
	state : null,
	curTabBut : null,
	curTabName : null,
	KsAttackTimer: null,
	sourceCity : {},
	destinationCity : {},
	rows : [],
	iused : new Array(),
	
	init : function (){
		var t = Movement;
		clearTimeout (t.displayTimer);
		paintMov = new CPopup ('pbWidMovement', 50, 50, 750, 800, true, Movement.close);
		paintMov.centerMe (mainPop.getMainDiv);
		paintMov.getMainDiv().innerHTML = '<DIV><DIV id="MovementBody" style="max-height:700px; max-width:750px; overflow:auto"></div>';
		paintMov.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.tabLabelMovement+'</DIV>';

		if (Movement.active){
			paintMov.show(false);
			Movement.active=false;
		} else {
			paintMov.show(true);
			Movement.active=true;
		}	
		t.show();
	},
	close: function(){
		var t = Movement;
		Movement.active=false;
		clearTimeout (t.displayTimer);
		t.state = null;
	},
	show : function (){
		var t = Movement;
		var rownum = 0;
		var ModelCity = {};
		//if (t.state == null) {
		if (true) {
			m = "<DIV class=pdxStat>"+culang.movementHead+"</div>"; //- <input type=button value='?' id=boaideattaquer class=buttonHelp>
			m +="<div id='statpourRAA'></div>";
			m += "<TABLE width=600 class=pdxTab border=0 align=center>\
           <tr><td colspan=4 align=center> <input type=button id=REEaction value='"+culang.scout+"'>&nbsp;<input type=button id=RAAaction value='"+culang.mainAttacking+"'>&nbsp;<input type=button id=RARaction value='"+culang.mainReassign+"'>&nbsp;<input type=button id=RENaction value='"+culang.mainReinforce+"'>&nbsp;<input type=button id=RENBaction value='"+culang.movementReinforceFood+"'></td></tr>\
		   <tr><td colspan=4><div id=ptRAAStatus style='overflow-y:auto; max-height:50px; border-bottom:1px solid #141516;'></div><span id='KsAttackProg'></span></td></tr>\
		   <tr><td colspan=4><INPUT type=checkbox id=ptmarch_autoknight "+(Options.marchautoknight?'CHECKED':'')+" /> "+culang.movementAutoSelectKnights+"</td></tr>\
		   <tr align=center valign=top><td colspan=1 width=130><b><u>"+culang.mainCastle+"</b></u><br><span id=RAAsrcRptspeedcity></span></td>\
           <td colspan=1><b><u>"+culang.mainTarget+"</b></u><br>X:<input type=text id=RAAtypetrpx size=3 title='"+culang.movementSourceNote+"'>&nbsp;Y:<input type=text id=RAAtypetrpy size=3 title='"+culang.movementSourceNote+"'><br><a href='javascript:void(0);' id='Kschargelistelieux' title='"+culang.movementAliianceMemberNote+"'>"+culang.mainPlayer+"</a>: <select id='listeFavori'></select></td>\
           <td><b><u>"+culang.mainDistance+"</u></b><br><span id='KsEstimationD'>&nbsp;</span><td><b><u>"+culang.movementNextCity+"</u></b><br><span id=KsVilleProche></span>\
           </tr><tr align=center valign=top>\
           <td colspan=4 align=left><table border=0 bordercolor=black cellspacing=0 cellpadding=0 width=100% style='text-align:center'><tr><td rowspan=18><div id=RAAstatsource></div></td><td colspan=2><a href='javascript:void(0)' id=Ks_RAZ_Units title='"+culang.movementClearTroopsNote+"'>"+culang.mainTroopAmount+"</a></td><td>"+culang.movementAttackETA+"</td><td>"+culang.movementReinforceETA+"</td></tr>";
			for (r=1; r<18; r++){
				m += '<tr><td align=right><img height=20 title="'+uW.unitcost['unt'+r][0]+'" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+r+'_30.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAnbunit'+r+'" type=text size=7 value="0" ></td><td><span id="KsEstimationTT'+r+'">&nbsp;</span></td><td><span id="KsEstimationTZ'+r+'">&nbsp;</span></td></tr>';
			}
			var itemlist=[55,57,931,932];
			var Ksitems="";
			for(var i=0;i<itemlist.length;i++){
				Ksitems += "<img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/"+itemlist[i]+".jpg' /><input type=checkbox id='Ksitem_"+itemlist[i]+"'><span id='KsitemSpan_"+itemlist[i]+"'>" + uW.ksoItems[itemlist[i]].count + "</span>&nbsp;";
			}
			m += "</table></td></tr>\
              <tr><td colspan=2><b><u>"+culang.mainKnights+"</u></b>: <SELECT id='RAApiKnight' type=list></select><br>"+Ksitems+"</td><td colspan=2><div id=Ksinfodest></div><center><input type=button value='"+culang.movementPlayerCheck+"' id=Ksrechdest></td></tr>\
              <tr><td colspan=4><b><div class=pdxStat>"+culang.movementHeadSavedAttacks+"</div></tr><tr><td colspan=2><select id=Ks_AT_Fav></select><input type=button value='"+culang.mainDelete+"' id=Ks_AT_Fav_Sup><input type=button value='"+culang.mainDeleteAll+"' id=Ks_AT_Fav_RESET></td><td colspan=2>"+culang.mainName+": <input type=type id='Ks_AT_Fav_Nom' size='10' maxlength='12' title='"+culang.movementSaveAttackName+"'>&nbsp;<input type=checkbox id=Ks_AT_Fav_Coo> <span title='"+culang.movementAutoAttackCoordNote+"'>"+culang.mainCoord+"</span> <input type=button value='"+culang.buttonSave+"' id=Ks_AT_Fav_ajou>\
              <tr><td colspan=4><b><div class=pdxStat>"+culang.movementHeadAutoAttack+"</div></tr><tr><td><input type=button id='KsActiveAttack' value='"+culang.mainAttack+" = "+culang.buttonOFF+"' ></td><td colspan=3><span id='KsCompAttack'></span></tr>\
              <tr><td><b><u>"+culang.mainArrival+"</u>:</b> <input type=text size=7 id='KsHorloge' value='" + Options.AttackHorloge + "' title='"+culang.movementAutoAttackArrivalNote+"'></td><td><input type=button value='"+culang.buttonSave+"' id='KsSaveAttack'></td><td><input type=button value='"+culang.buttonEdit+"' id='KsEditAttack' disabled></td></tr>\
              <tr><td colspan=4></td></tr></table>";
			ById('MovementBody').innerHTML = m;
			t.statpourRAA = ById ('statpourRAA');
			t.Favoris = ById('Ks_AT_Fav');
			t.Ksinfodest = ById('Ksinfodest');
			t.Ksrechdest = ById("Ksrechdest");
			// ById('boaideattaquer').addEventListener('click', function(){
			// window.open(homePage+" ");
			// } , false);
			t.Ksrechdest.addEventListener ('click', function() {
				t.rechercheDEST();
			}, false);
			function savedAttacks() {
				t.Favoris.innerHTML="<option value=''>-- "+culang.mainSelect+" --</option>";
				var lisf = Options.AttackFav;
				for (var m in lisf) {
					var lis = lisf[m];
					if (lis!=null)
						t.Favoris.innerHTML+="<option value='"+m+"'>"+lis[0]+"</option>";
				}
			}
			ById("ptmarch_autoknight").addEventListener('click', function(){
				Options.marchautoknight = this.checked;
				saveOptions();
				t.show();
			},false);
			ById("Ks_AT_Fav_RESET").addEventListener ('click', function() {
				Options.AttackFav={};
				saveOptions();
				savedAttacks();
			}, false);
			ById("Ks_AT_Fav_Sup").addEventListener ('click', function() {
				numfav=ById("Ks_AT_Fav").value;
				if (numfav!="") {
					Options.AttackFav[numfav]={};
					delete Options.AttackFav[numfav];
					saveOptions();
					savedAttacks();
				}
			}, false);
			ById("Ks_RAZ_Units").addEventListener ('click', function() {
				for (r=1; r<18; r++) ById("RAAnbunit"+r).value=0;
			}, false);
			ById("Ks_AT_Fav_ajou").addEventListener ('click', function() {
				if (ById("Ks_AT_Fav_Nom").value=="") {
					alert(""+culang.movementSaveAttackNamePopup+"");
					return;
				}
				var a =ById("Ks_AT_Fav_Nom").value;
				Options.AttackFav[a]={};
				var lisf = Options.AttackFav[a];
				lisf[0]=ById("Ks_AT_Fav_Nom").value;
				for (r=1; r<18; r++) lisf[r]=ById("RAAnbunit"+r).value;
				if (ById("Ks_AT_Fav_Coo").checked) {
					lisf[19]=t.destinationCityx.value;
					lisf[20]=t.destinationCityy.value;

				}
				ById("Ks_AT_Fav_Coo").checked=false;
				ById("Ks_AT_Fav_Nom").value="";
				saveOptions();
				savedAttacks();
			}, false);
			ById("Ks_AT_Fav").addEventListener ('change', function() {
				numfav=ById("Ks_AT_Fav").value;
				if (numfav=="") {
					for (r=1; r<18; r++) ById("RAAnbunit"+r).value=0;
				}else {
					var lisf = Options.AttackFav[numfav];
					for (var m in lisf) {
						if(m>0 && m<18)
							if (ById("RAAnbunit"+m)) ById("RAAnbunit"+m).value=lisf[m];
						if (m==19)
							if (lisf[m]>0)
								t.destinationCityx.value=lisf[m];
						if (m==20)
							if (lisf[m]>0)
								t.destinationCityy.value=lisf[m];
					}
				}
			}, false);
			ById("Ksitem_55").addEventListener ('click', function() {
				ById("Ksitem_57").checked=false;
				t.estimerRes();
			}, false);
			ById("Ksitem_57").addEventListener ('click', function() {
				ById("Ksitem_55").checked=false;
				t.estimerRes();
			}, false);
			t.statutRAA = ById ('ptRAAStatus');
			t.destinationCityx = ById ('RAAtypetrpx');
			t.destinationCityy = ById ('RAAtypetrpy');
			t.destinationCityx.value = Options.Xrenfort;
			t.destinationCityy.value = Options.Yrenfort;
			if (!Options.tabmovementopen) { 
					if (ById ('maparea_map').style.display!="none") {
						t.destinationCityx.value = ById ('mapXCoor').value;
						t.destinationCityy.value = ById ('mapYCoor').value;
						t.rechercheDEST();
					}
			}
			t.listeFavoris = ById ('listeFavori');
			t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);
			t.chargelistelieux = ById ('Kschargelistelieux');
			t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
			t.actionREN = ById ('RENaction');
			t.actionRENB = ById ('RENBaction');
			t.actionREE = ById ('REEaction');
			t.actionRAA = ById ('RAAaction');
			t.actionRAR = ById ('RARaction');
			t.actionREN.addEventListener ('click', function () { t.clickATTAQUEDo(2,0); }, false);
			t.actionRAA.addEventListener ('click',  function () { t.clickATTAQUEDo(4,0); }, false);
			t.actionRAR.addEventListener ('click',  function () { t.clickATTAQUEDo(5,0); }, false);
			t.actionRENB.addEventListener ('click',  function () { t.clickATTAQUEDo(2,1); }, false);
			t.actionREE.addEventListener ('click',  function () { t.clickATTAQUEDo(3,0); }, false);
			t.destinationCityx.addEventListener ('keyup', function () { t.estimerRes(); }, false);
			t.destinationCityy.addEventListener ('keyup', function () { t.estimerRes(); }, false);
			var dcp0 = new CdispCityPicker ('ptRAA0', ById('RAAsrcRptspeedcity'), false, t.clickRAACitySourceSelect, Cities.byID[uW.currentcityid].idx);
			t.state = 1;
			t.estimerRes();
			t.KsAttackProg = ById ('KsAttackProg');
			t.KsHorloge = ById ('KsHorloge');
			t.KsSaveAttack = ById ('KsSaveAttack');
			t.KsEditAttack = ById ('KsEditAttack');
			t.KsCompAttack = ById ('KsCompAttack');
			t.KsActiveAttack  = ById ('KsActiveAttack');
			t.KsActiveAttack.addEventListener ('click', t.AutoattackOnOff, false);
			t.KsSaveAttack.addEventListener ('click', function () {
				var itemlist=[55,57,931,932];
				for(var i=0;i<itemlist.length;i++){
					ById('KsitemSpan_'+itemlist[i]).checked=false;
				}
				t.enregistreAttack();
			}, false);
			if (Options.AttackCibleX!=0 && Options.AttackCibleY!=0) {
				t.KsEditAttack.disabled=false;
			}
			t.KsEditAttack.addEventListener ('click', function () {
				t.destinationCityx.value = Options.AttackCibleX;
				t.destinationCityy.value = Options.AttackCibleY;
				ById("RAApiKnight").value=Options.AttackKnight;
				nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
				for (r=1; r<18; r++) {
					ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
				}
			}, false);
			savedAttacks();
			if (Options.AttackOnOff) {
				t.KsActiveAttack.value=''+culang.mainAttack+' = '+culang.buttonON;
				t.activeAttack();
			}
		}
	},
	MapAjax : new CMapAjax(),
	rechercheDEST:function() {
		var t = Movement;
		t.Ksinfodest.innerHTML="<center>"+culang.movementPlayerCheckSearch+"</center>";
		var xcoord=t.destinationCityx.value;
		var ycoord=t.destinationCityy.value;
		t.MapAjax.request (xcoord, ycoord, 1, function(left, top, width, rslt) {
			map = rslt.data;
			for (k in map){
				if (xcoord==map[k].xCoord && ycoord==map[k].yCoord) {
					var m="";
					var uid=map[k].tileUserId;
					if (uid==null || uid==0 || uid=="0") {
						t.Ksinfodest.innerHTML="<center><span class='boldRed'>"+culang.mainNotAvailable+"</span></center>";
						return;
					}
					var params = uW.Object.clone(uW.g_ajaxparams);
					params.checkArr = uid;
					new MyAjaxRequest(uW.g_ajaxpath + "ajax/getOnline.php" + uW.g_ajaxsuffix, {
						method: "post",
						parameters: params,
						onSuccess: function (rslt) {
							var p = rslt.data;
							if (p[uid] == true) {
								m = '<span style="color:green"><b>'+culang.movementPlayerCheckOn+'</b></span>';
							} else {
								m = '<center><span style="color:red"><b>'+culang.movementPlayerCheckOff+'</b></span>';
							}
							var params = uW.Object.clone(uW.g_ajaxparams);
							params.pid = uid;
							new MyAjaxRequest(uW.g_ajaxpath + "ajax/viewCourt.php" + uW.g_ajaxsuffix, {
								method: "post",
								parameters: params,
								onSuccess: function (rslt) {
									t.Ksinfodest.innerHTML="<center><b>" + rslt.playerInfo.displayName+"</b><BR>"+m;
								},
								onFailure: function (rslt) {},
							});
						},onFailure: function (rslt) {},
					});
				}
			}
		});
	},
	AutoattackOnOff:function() {
		var t = Movement;
		t.KsCompAttack.innerHTML='';
		clearTimeout (t.KsAttackTimer);
		if (t.KsActiveAttack.value==''+culang.mainAttack+' = '+culang.buttonOFF+'') {
			t.KsActiveAttack.value=''+culang.mainAttack+' = '+culang.buttonON;
			Options.AttackOnOff = true;
			saveOptions();
			t.activeAttack();

		} else {
			Options.AttackOnOff = false;
			saveOptions();
			t.KsActiveAttack.value=''+culang.mainAttack+' = '+culang.buttonOFF;
		}
	},
	activeAttack:function() {
		var t = Movement;
		clearTimeout (t.KsAttackTimer);
		if (Options.AttackGoHorloge) {
			var depart=new Date()
			depart.setTime(Options.AttackGoHorloge);
			var now = unixTime()*1000;
			if (now >= Options.AttackGoHorloge) {
				t.KsCompAttack.innerHTML='<center><font color=red>'+culang.movementAutoAttackDone+'</font></center>';// ACTIONLOG
				t.destinationCityx.value = Options.AttackCibleX;
				t.destinationCityy.value = Options.AttackCibleY;
				ById("RAApiKnight").value=Options.AttackKnight;
				nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
				for (r=1; r<18; r++) {
					ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
				}
				t.clickATTAQUEDo(4,0);
				clearTimeout (t.KsAttackTimer);
				Options.AttackGoHorloge=null;
				Options.AttackOnOff = false;
				saveOptions();
				return;
			}
			if (now > depart.getTime()) {
				t.KsCompAttack.innerHTML='<center><font color=red>'+culang.movementAutoAttackNotPossible+'</font></center>';
				clearTimeout (t.KsAttackTimer);
				Options.AttackGoHorloge=null;
				saveOptions();
				return false;
			}
			t.KsAttackTimer=setTimeout(function(){
				var depart=new Date();
				depart.setTime(Options.AttackGoHorloge);
				var now = unixTime()*1000;
				var tempsrestant = depart.getTime() - now;
				t.KsCompAttack.innerHTML='<center><font color=red><b>'+culang.movementAutoAttackIn+' '+timestr(tempsrestant/1000)+'</b></font></center>';
				t.activeAttack();
			},1000);
		}
	},
	enregistreAttack : function() {
		var t = Movement;
		if (t.KsHorloge.value.match("^[0-9]{2}:[0-9]{2}:[0-9]{2}$")) {
			var horloge = t.KsHorloge.value;
			Options.AttackHorloge = horloge;
			var ndate=new Date();
			ndate.setHours(horloge.substr(0,2));
			ndate.setMinutes(horloge.substr(3,2));
			ndate.setSeconds(0);
			var atunits=new Array();
			for (r=1; r<18; r++) {
				atunits.push(parseInt(ById("RAAnbunit"+r).value));
			}
			Options.AttackUnits = atunits;
			Options.AttackFromCity = t.sourceCity.id;
			Options.AttackKnight = ById("RAApiKnight").value;
			Options.AttackCibleX = t.destinationCityx.value;
			Options.AttackCibleY = t.destinationCityy.value;

			var x1 = parseInt(t.sourceCity.x);
			var x2 = parseInt(t.destinationCityx.value);
			var y1 = parseInt(t.sourceCity.y);
			var y2 = parseInt(t.destinationCityy.value);
			var dist = distance (x1, y1, x2, y2);
			var tempplusgrand=0;
			for (r=1; r<18; r++){
				if (parseInt(ById("RAAnbunit"+r).value)>0) {
					var m = estETA(dist, r, t.sourceCity.id,4);
					if (tempplusgrand<m.ETA) tempplusgrand=m.ETA;
				}
			}
			var departtime=ndate.getTime() - (tempplusgrand*1000);
			var depart=new Date()
			depart.setTime(departtime);
			var now = unixTime()*1000;
			if (now > depart.getTime()) {
				t.KsAttackProg.innerHTML = ""+culang.movementMarchNotPossible+"";
				return false;
			}
			Options.AttackGoHorloge =  depart.getTime();
			saveOptions ();
			t.KsAttackProg.innerHTML = ""+culang.movementAutoAttackSend+" " + Options.AttackCibleX + ","+ Options.AttackCibleY +" "+culang.movementAutoAttackSend2+"";
			t.KsEditAttack.disabled=false;
		} else {
			t.KsAttackProg.innerHTML = ""+culang.movementWrongTimeFormat+"";
		}
	},
	clickATTAQUEDo: function(typemarche, bouffe) {
		var t = Movement;
		var totalunit=0;
		if (typemarche==3 && ById("RAAnbunit3").value==0) ById("RAAnbunit3").value=1;
		for (r=1; r<18; r++){
			if (typemarche==3 && r!=3) {
				ById("RAAnbunit"+r).value=0;
			}
			if (parseInt(ById("RAAnbunit"+r).value) > parseInt(ById("RAAdestunit"+r).value)) {
				ById("RAAnbunit"+r).style.backgroundColor="red";
				return false;
			}
			totalunit=totalunit+parseInt(ById("RAAnbunit"+r).value);
			ById("RAAnbunit"+r).style.backgroundColor="";
		}
		var errMsg = "";
		if (isNaN (t.destinationCityx.value) ||t.destinationCityx.value<0 || t.destinationCityx.value>749)
			errMsg = ""+culang.movementXMustBe+"<BR>";
		if (isNaN (t.destinationCityy.value) || t.destinationCityy.value<0 || t.destinationCityy.value>749)
			errMsg += ""+culan.movementYMustBe+"<br>";

		if (ById("RAApiKnight").value==0 && typemarche==4) {
			errMsg += ""+culang.movementErrorSelectKnight+"<BR>";
		}
		if (errMsg != "") {
			t.statutRAA.innerHTML = "<FONT COLOR=#550000>"+ errMsg +"</font>";
			return;
		}
		var x=t.destinationCityx.value;
		var y=t.destinationCityy.value;
		t.SaveCoordsOptions(x,y);
		var RInfo = getRallypointInfo(t.sourceCity.id);
		var maxtroupe = RInfo.maxMarchSize;
		var l_elem = ById("Ksitem_931");
		if(l_elem && l_elem.checked && parseInt(Seed.items["i931"]) > 0) {
			var maxtroupe = RInfo.maxMarchSize25;
		}
		var l_elem = ById("Ksitem_932");
		if(l_elem && l_elem.checked && parseInt(Seed.items["i932"]) > 0) {
			var maxtroupe = RInfo.maxMarchSize50;
		}
		if (totalunit==0) {
			t.statutRAA.innerHTML = '<FONT COLOR=#550000>'+culang.movementErrorNoTroops+'</font>';
			return;
		}
		if (totalunit > maxtroupe) {
			t.statutRAA.innerHTML = '<FONT COLOR=#550000>'+culang.movementErrorNoFreeSlots+' <span class="boldRed">'+maxtroupe+'</span> '+culang.movementErrorNoFreeSlots2+'</font>';
			return;
		}
		var params = uW.Object.clone(uW.g_ajaxparams);		
		var iused=new Array();
		var itemlist=[55,57,931,932];
		for(var i=0;i<itemlist.length;i++){

			var l_elem=ById("Ksitem_"+itemlist[i]);
			if(l_elem&&l_elem.checked&&parseInt(Seed.items["i"+itemlist[i]])>0){
				iused.push(itemlist[i]);
			}
		}
		var res=0;
		if (bouffe==1) {
			for (var i=1;i<18;i++) {
				res += parseInt(uW.unitstats['unt'+i][5] * ById("RAAnbunit"+i).value * (1 + (0.10 * Seed.tech.tch10)));
			}
		}
		params.items=iused.join(",");
		params.cid= t.sourceCity.id;
		params.type = typemarche;
		params.xcoord = x;
		params.ycoord = y;
		if (typemarche==3)
			params.kid=0;
		else
			params.kid= ById("RAApiKnight").value;
		params.r1 = res;
		params.u1 = 0;
		params.u2 = 0;
		params.u3 = 0;
		params.u4 = 0;
		params.u5 = 0;
		params.u6 = 0;
		params.u7 = 0;
		params.u8 = 0;
		params.u9 = 0;
		params.u10 = 0;
		params.u11 = 0;
		params.u12 = 0;
		params.u13 = 0;
		params.u14 = 0;
		params.u15 = 0;
		params.u16 = 0;
		params.u17 = 0;
		if (typemarche!=3) {
			if (ById("RAAnbunit1").value>0) params.u1 = ById("RAAnbunit1").value;
			if (ById("RAAnbunit2").value>0) params.u2 = ById("RAAnbunit2").value;
			if (ById("RAAnbunit3").value>0) params.u3 = ById("RAAnbunit3").value;
			if (ById("RAAnbunit4").value>0) params.u4 = ById("RAAnbunit4").value;
			if (ById("RAAnbunit5").value>0) params.u5 = ById("RAAnbunit5").value;
			if (ById("RAAnbunit6").value>0) params.u6 = ById("RAAnbunit6").value;
			if (ById("RAAnbunit7").value>0) params.u7 = ById("RAAnbunit7").value;
			if (ById("RAAnbunit8").value>0) params.u8 = ById("RAAnbunit8").value;
			if (ById("RAAnbunit9").value>0) params.u9 = ById("RAAnbunit9").value;
			if (ById("RAAnbunit10").value>0) params.u10 = ById("RAAnbunit10").value;
			if (ById("RAAnbunit11").value>0) params.u11 = ById("RAAnbunit11").value;
			if (ById("RAAnbunit12").value>0) params.u12 = ById("RAAnbunit12").value;
			if (ById("RAAnbunit13").value>0) params.u13 = ById("RAAnbunit13").value;
			if (ById("RAAnbunit14").value>0) params.u14 = ById("RAAnbunit14").value;
			if (ById("RAAnbunit15").value>0) params.u15 = ById("RAAnbunit15").value;
			if (ById("RAAnbunit16").value>0) params.u16 = ById("RAAnbunit16").value;
			if (ById("RAAnbunit17").value>0) params.u17 = ById("RAAnbunit17").value;
		}else {
			params.u3 = ById("RAAnbunit3").value;
			ById("RAAnbunit3").value=0;
		}
		t.actionRAA.disabled=true;
		t.actionREN.disabled=true;
		t.actionREE.disabled=true;
		t.statutRAA.innerHTML = "<center><i><b>"+culang.movementInWork+"</b></i></center>";
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var t = Movement;
				var rslt = transport;
				if (rslt.ok) {
					var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
          var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
							unitsarr[i] = params["u"+i];
						}
					}
					var resources=new Array();
					resources[0] = params.gold;
					for(i=1; i<=4; i++){
						resources[i] = params["r"+i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};

					for(var i=0;i<iused.length;i++){
						Seed.items["i"+iused[i]]=parseInt(Seed.items["i"+iused[i]])-1;
						uW.ksoItems[iused[i]].subtract();
					}
					var typeattaque = "";
					switch (typemarche){
						case 2:
							typeattaque="<span class='boldGreen'>"+culang.movementReinforceOK+"</span>";
							break;
						case 3:
							typeattaque="<span class='boldGreen'>"+culang.movementScoutOK+"</span>";
							break;
						case 4:
							typeattaque="<span class='boldRed'>"+culang.movementAttackOK+"</span>";
							break;
						case 5:
							typeattaque="<span class='boldGreen'>"+culang.movementReassignOK+"</span>";
							break;
						default:
							typeattaque="<span class='boldGreen'>"+culang.movementMarchOK+"</span>";
					}
					t.statutRAA.innerHTML = "<center><font size='3px'><i><b>"+typeattaque+"</b></i></font></center>";
					t.actionRAA.disabled=false;
					t.actionREE.disabled=false;
					t.actionREN.disabled=false;
					t.clickRAACitySourceSelect(t.sourceCity);
				} else {
					if (rslt.user_action) {
						t.statutRAA.innerHTML ="<font color=red size='3px'><b"+culang.movementCaptchaAlert+"<b></font>";
						t.actionRAA.disabled=false;
						t.actionREN.disabled=false;
						t.actionREE.disabled=false;
					} else {
						t.statutRAA.innerHTML ="<font color=red size='3px'><b><i>"+culang.movementErrorTryAgain+"</i></b></font>";
						if (rslt.msg) {
							t.statutRAA.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";

							t.actionRAA.disabled=false;
							t.actionREN.disabled=false;
							t.actionREE.disabled=false;
						}else{
							t.statutRAA.innerHTML +="<br><center>"+culang.mainError+"</center></font>";
							t.actionRAA.disabled=false;
							t.actionREN.disabled=false;
							t.actionREE.disabled=false;
						}
					}
				}
			},
			onFailure: function () {
				var t = Movement;
				t.statutRAA.innerHTML ="<font color=red size='3px'><b><i>"+culang.movementErrorTryAgain+"</i></b></font>";
				t.actionRAA.disabled=false;
				t.actionREN.disabled=false;
				t.actionREE.disabled=false;
			}
		});
	},
	estimerRes: function() {
		var t = Movement;
		var x1 = parseInt(t.sourceCity.x);
		var x2 = parseInt(t.destinationCityx.value);
		var y1 = parseInt(t.sourceCity.y);
		var y2 = parseInt(t.destinationCityy.value);
		var dist = distance (x1, y1, x2, y2);
		ById("KsEstimationD").innerHTML = '<b>' + dist + '</b>&nbsp;<a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ t.destinationCityx.value +','+ t.destinationCityy.value +')</a>';
		for (r=1; r<18; r++){
			var m = estETA(dist, r, t.sourceCity.id,4);
			ById("KsEstimationTT"+r).innerHTML = "<b>" + m.etaStr + "</b>";
			var m = estETA(dist, r, t.sourceCity.id,2);
			ById("KsEstimationTZ"+r).innerHTML = "<b>" + m.friendEtaStr + "</b>";
		}
		var closestDist=999999;
		var closestLoc=null;
		var closestNum=1;
		for (var c=0; c<Cities.numCities; c++){
			var city = Cities.cities[c];
			var dist=distance(city.x,city.y,x2,y2);
			if(dist<closestDist) {
				closestDist=dist;
				closestLoc=city.x +','+ city.y;
				closestNum=c+1;
			}
		}
		ById("KsVilleProche").innerHTML='<input type="submit" value="'+closestNum+'" class="castleBut castleButNon">'
	},
	SelectFavoris:function() {
		var t = Movement;
		if (t.listeFavoris.value!='') {
			var valeur=t.listeFavoris.value;
			var x=valeur.substr(0, valeur.lastIndexOf(','));
			var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
			t.destinationCityx.value = x;
			t.destinationCityy.value = y;
		}
		t.estimerRes();
	},
	chercherFavoris: function() {
		var t = Movement;
		var myA = getMyAlliance ();
		if (myA[0]!=0) {
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.perPage = 100;
			params.allianceId = myA[0];
			params.type = 'might';
			params.page = 1;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/getUserLeaderboard.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					if (rslt.ok){
						var z=0;
						var m="";
						for (var i=0; i<rslt.results.length; i++){
							p = rslt.results[i];
							if (p.userId != 0){
								for (var c=0; c<p.cities.length; c++){
									if (Seed.player.name!=p.displayName) {
										m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - "+culang.mainCity+" " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
									}
								}
							}
						}
						t.listeFavoris.innerHTML="<option value=''>-- "+culang.mainSelect+" --</option>"+m;
					}
				},
				onFailure: function (rslt) {
					t.listeFavoris.innerHTML="<option>"+culang.mainError+"</option>";
				},
			});
		} else {
			t.listeFavoris.innerHTML="<option>"+culang.movementSelectErrorNoAlliance+"</option>";
		}
	},
	SaveCoordsOptions: function(x,y) {
		Options.Xrenfort = x;
		Options.Yrenfort = y;
		saveOptions ();
	},
	clickRAACitySourceSelect : function (city){
		var t = Movement;
		if (t.sourceCity!=city) {
			t.sourceCity = city;
		}
		var m="";
		m="<table cellspacing=0 cellpadding=0 width=80%><tr><td colspan=2><b><u>"+culang.mainTroopAmount+"</u></b></tr>";
		var cityID = 'city'+ t.sourceCity.id;
		for (r=1; r<18; r++){
			m += '<tr><td align=right><img title="'+uW.unitcost['unt'+r][0]+'" height=20 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+r+'_30.jpg></td>\
             <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAdestunit'+r+'" type=text size=7 readonly value="'+parseInt(Seed.units[cityID]['unt'+r])+'">&nbsp;\
             <input type=button value=">" id="RAApdestunit'+r+'"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
		}
		m += "</table>";
		ById("RAAstatsource").innerHTML = m;
		var knt = new Array();
		for (k in Seed.knights['city' + t.sourceCity.id]){
			if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]){
				knt.push ({
					Name:   Seed.knights['city' + t.sourceCity.id][k]["knightName"],
					Combat:	Seed.knights['city' + t.sourceCity.id][k]["combat"],
					ID:	Seed.knights['city' + t.sourceCity.id][k]["knightId"],
				});
			}
		}
		knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
		ById('RAApiKnight').innerHTML="";
		var o = document.createElement("option");
		o.text = uW.g_js_strings.modal_attack.dchooseknightd;
		o.value = 0;
		ById("RAApiKnight").options.add(o);
		for (k in knt){
			if (knt[k]["Name"] !=undefined){
				var o = document.createElement("option");
				o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
				o.value = knt[k]["ID"];
				ById("RAApiKnight").options.add(o);
			}
		}
		if (ById('RAApiKnight').options.length>0) {
			if(Options.marchautoknight)
				ById('RAApiKnight').selectedIndex=1;
		}

		var itemlist=[55,57,931,932];
		for(var i=0;i<itemlist.length;i++){
			ById('KsitemSpan_'+itemlist[i]).innerHTML = uW.ksoItems[itemlist[i]].count;
		}
		for (r=1; r<18; r++){
			ById("RAApdestunit"+r).addEventListener ('click', function() {
				var nomcha=this.id.replace("RAApdest","RAAdest");
				var nomcha2=this.id.replace("RAApdestunit","RAAnbunit");
				ById(nomcha2).value=0;
				var RInfo = getRallypointInfo(t.sourceCity.id);
				var maxtroupe = RInfo.maxMarchSize;
				var l_elem = ById("Ksitem_931");
				if(l_elem && l_elem.checked && parseInt(Seed.items["i931"]) > 0) {
					var maxtroupe = RInfo.maxMarchSize25;
				}
				var l_elem = ById("Ksitem_932");
				if(l_elem && l_elem.checked && parseInt(Seed.items["i932"]) > 0) {
					var maxtroupe = RInfo.maxMarchSize50;
				}
				var nbunitto=0;
				for (r=1; r<18; r++) {
					nbunitto+=parseIntNan(ById("RAAnbunit"+r).value);
				}
				var libre = parseIntNan(maxtroupe - nbunitto);
				if (ById(nomcha).value>=libre) {
					ById(nomcha2).value = libre;
				}  else {
					ById(nomcha2).value= ById(nomcha).value;
				}
			}, false);
		}
		if (t.sourceCity!=city) {
			for (r=1; r<18; r++){
				ById("RAAnbunit"+r).value="0";
			}
		} else {
			for (r=1; r<18; r++){
				if (ById("RAAnbunit"+r).value=="") ById("RAAnbunit"+r).value="0";
				if (ById("RAAdestunit"+r).value=="") ById("RAAdestunit"+r).value="0";
				if (parseInt(ById("RAAnbunit"+r).value)>parseInt(ById("RAAdestunit"+r).value)) {
					ById("RAAnbunit"+r).value="0";
				}
			}
		}
		t.estimerRes();
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Gifts.js">
//	
//	   KOC POWER - TABS2 GIFTS											        
//	
Tabs2.Gifts = {
	cont : null,
	kdodisp:{},
	amis: [],
	init : function (){
		var t = Tabs2.Gifts;
		t.cont = document.createElement('div');
		return t.cont;
	},
	getContent : function (){
		var t = Tabs2.Gifts;
		return t.cont;
	},
	hide : function (){
		var t = Tabs2.Gifts;
	},
	show : function (){
		var t = Tabs2.Gifts;
		var  m = "<DIV class=pdxStat>"+culang.giftsHead+"</div>";
		m+="<br>"+culang.giftsGifts+" <select id=KsKdoSel>";
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = "GiftItems";
		params.action = "getGiftItems";
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok){
					t.kdodisp = rslt.giftItems;
					for (k in t.kdodisp) {
						if (t.kdodisp[k].itemId) {
							if (Options.KDODef == 0) {
								Options.KDODef = t.kdodisp[k].itemId;
							}
							m+="<option value='"+t.kdodisp[k].itemId+"' "+ (Options.KDODef==t.kdodisp[k].itemId?'SELECTED ':'') +">"+unsafeWindow.ksoItems[t.kdodisp[k].itemId].name+"</option>";
						}
					}
					m+="</select>&nbsp;";
					m+="<input type='button' value='"+culang.giftsButtonSend+"' id=KsKdoSendBtn><HR><div style='max-height:1000px;' id=KsKdoResult></div>";
					t.cont.innerHTML = m;
					ById("KsKdoSel").addEventListener('change', function(e){ Options.KDODef=ById("KsKdoSel").value;saveOptions(); },false);
					ById("KsKdoSendBtn").addEventListener('click', function(e){ t.listMembers(); },false);
				}
			}
		});
	},
	
	listMembers:function() {
		var t = Tabs2.Gifts;
		t.amis=[];
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.ctrl = "allianceGifting\\AllianceGiftingServiceAjax";
		params.action = "getRecipients";
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				var rsp=rslt.recipients;
				if (!Options.KDODefUsers) {Options.KDODefUsers = []; saveOptions();}
				var m = '<table>';
				var c = 0;
				for (k in rsp) {
					var member = rsp[k];
					if (member.userId) {
						c++;
						if (c == 1) m+='<tr>';
						if (Options.KDODefUsers.contains(member.userId)) {
							m+='<td><input id="KsKdo_'+member.userId+'" type="checkbox" checked></td>';			
						} else {
							m+='<td><input id="KsKdo_'+member.userId+'" type="checkbox"></td>';						
						}
						if (member.playerSex == 'F') {
							m+='<td><img height="30" src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/avatars/v2/50/f'+member.avatarId+'.png"></td>';
							m+='<td width="150">'+uW.g_js_strings.commonstr.lady+' '+member.displayName+'</td>';
						} else {
							m+='<td><img height="30" src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/avatars/v2/50/m'+member.avatarId+'.png"></td>';
							m+='<td width="150">'+uW.g_js_strings.commonstr.lord+' '+member.displayName+'</td>';
						}
						if (c == 4) {
							m+='</tr>';
							c = 0;
						}
						t.amis.push(member.userId);
					}
				}
				m+= '</tr></table>';
				m+= '<br><b>'+rslt.freeSlot+' '+culang.giftsfreeSlot+'&nbsp;<span id="KsKdoCounter"></span></b><br>';
				m+= "<br><input type='submit' value='"+culang.giftsButtonSend+"' id='KsKdoSendBtnFinal'>&nbsp;<span id='KsKdoResult2'></span><br><br>";
				ById("KsKdoResult").innerHTML=m;
				//ById("KsKdoResult").innerHTML+= '<pre>'+inspect(rslt,9)+'</pre>';
				ById("KsKdoSendBtnFinal").addEventListener('click', function(e){ t.sendGift(); },false);
				var counter = 0;
				for (k in rsp) {
					var member = rsp[k];
					if (member.userId) {
						var m = ById("KsKdo_"+member.userId);
						if (m.checked) {
							m.parentNode.style.backgroundColor = 'rgb(255, 255, 180)';
							m.parentNode.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
							m.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
							counter++;
						} else {
							m.parentNode.style.backgroundColor = 'rgb(246, 243, 236)';
							m.parentNode.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
							m.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
						}
						ById("KsKdo_"+member.userId).addEventListener('click', function(e){ 
							var t = Tabs2.Gifts;
							var id = this.id.split('_')[1];
							if (this.checked) {
								Options.KDODefUsers.push(id);
								this.parentNode.style.backgroundColor = 'rgb(255, 255, 180)';
								this.parentNode.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
								this.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
							} else {
								for (var i = 0; i < Options.KDODefUsers.length; i++) {
									if (Options.KDODefUsers[i] == id) {
										Options.KDODefUsers.splice(i,1);
										break;
									}
								}
								this.parentNode.style.backgroundColor = 'rgb(246, 243, 236)';
								this.parentNode.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
								this.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
							}
							saveOptions();
							var counter = 0;
							for (var i = 0; i < t.amis.length; i++) {
								var m = ById("KsKdo_"+t.amis[i]);
								if (m.checked) counter++;
							}
							var rep = {'counter': counter};
							ById("KsKdoCounter").innerHTML = culang.giftscounter.mreplace(rep);
						},false);
					}
				}
				if (counter > 0) {
					var rep = {'counter': counter};
					ById("KsKdoCounter").innerHTML = culang.giftscounter.mreplace(rep);
				}
			},
		});
	},
	
	sendGift: function() {
		var t = Tabs2.Gifts;
		var counter = 0;
		if (Options.KDODefUsers.length > 0) {
			var amis = "";
			for (var i = 0; i < Options.KDODefUsers.length; i++) {
				if (t.amis.contains(Options.KDODefUsers[i])) {
					amis += Options.KDODefUsers[i] + "|";
					counter++;
				}
			}
		}
		if (counter > 0) {
			amis = amis.substring(0,amis.length-1);
			var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			params.ctrl = "allianceGifting\\AllianceGiftingServiceAjax";
			params.action = "sendGift";
			params.itemId=Options.KDODef;
			params.recipients = amis;
			new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",  parameters: params,
				onSuccess: function (rslt) {
					ById("KsKdoResult2").innerHTML="<span class=boldRed>"+counter + "</span> <span class=boldGreen>"+culang.giftsResultOK+"</span>";
				},
			});
		} else {
			ById("KsKdoResult2").innerHTML="<span class=boldRed>"+culang.giftsNotOK+"</span>";
		}
	},
}

//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Resources.js">
//	
//	   KOC POWER - TABS2 RESSOURCE										        
//	
 

Tabs2.Resources = {
	cont:null,
	resource:null,
	users : [],
	doList : [], // list of gifts to accept
	accepting : false,
	city : null,
	total : {gold:0, 1:0, 2:0, 3:0, 4:0},


	init : function (){
		var t = Tabs2.Resources;
		t.resource = {1:uW.g_js_strings.commonstr.food, 
									2:uW.g_js_strings.commonstr.wood, 
									3:uW.g_js_strings.commonstr.stone, 
									4:uW.g_js_strings.commonstr.ore};
		this.cont = document.createElement('div');
		return this.cont;
	},
	show : function (){
		var t = Tabs2.Resources;
		this.cont.style.overflowY = 'auto';
		this.cont.innerHTML = '<DIV class=pdxStat>'+culang.ressourceHead+'</div><TABLE cellpadding=0 cellspacing=0 class=pdxTab width=100%><TR><TD align=center><INPUT id="pballlist" type=submit value="'+uW.g_js_strings.commonstr.alliance+'" \><INPUT id="pballlist2" type=submit value="'+culang.mainFriends+'" \></td></tr></table>\
    <DIV id=resDiv style="width:100%; max-height:300px;">';
		ById('pballlist').addEventListener ('click', function() { t.e_clickfetchlist(1); }, false);
		ById('pballlist2').addEventListener ('click', function() { t.e_clickfetchlist(2); }, false);
	},

	hide : function (){
	},

	progress : function (msg, span, add){
		if(add)
			ById(span).innerHTML+=msg;
		else
			ById(span).innerHTML=msg;
	},

	e_clickfetchlist : function  (tt){     // (also cancel accepting)
		var t = Tabs2.Resources;
		t.users = [];
		if (t.accepting){
			ById('pballlist').value = ''+uW.g_js_strings.commonstr.alliance+'';
			ById('resDiv').innerHTML+= '<BR><SPAN class=boldRed>'+culang.mainCanceled+'</span>';
			t.accepting = false;
			return;
		}
		if (tt==1) ById('resDiv').innerHTML = '<div class=pdxStat>'+culang.ressourceCheckCourtsAlliace+'</div>'+culang.ressourceSearchAlliance+' <span id=pbResUserListCount></span>';
		if (tt==2) ById('resDiv').innerHTML = '<div class=pdxStat>'+culang.ressourceCheckCourtsFriends+'</div>'+culang.ressourceSearchFriends+' <span id=pbResUserListCount></span>';

		t.fetchUserList (tt, gotUserList);
		function gotUserList(userList){
			if(userList.length < 1){
				listGifts();
				return;
			}
			ById('resDiv').innerHTML += '<BR><b><i>'+culang.ressourceCheckCourts+'</i></b> <span id=pbResUserAvailCount></span>';
			t.checkDailyAction(userList, listGifts);
		}

		function listGifts (){
			t.city = Cities.cities[0];
			var m = '<DIV class=pdxStat><CENTER>'+culang.mainPlayer+': '+ t.users.length +'</center></div>';
			if (t.users.length<1){
				ById('resDiv').innerHTML = m + '<BR><CENTER><i><b>'+culang.ressourceSearchNone+'</b></i></center>';
				return;
			}
			m += '<TABLE class=pdxTab align=center><TR><TD align=right><b>'+culang.mainCastle+'</b>: </td><TD id=pbrescityselspan></td></tr>\
			<TR><TD align=right>'+culang.mainRessources+': </td><TD>'+ htmlSelector (t.resource, Options.getResType, 'id=pbResColType')	+ '</td></tr><TR><TD>'+culang.mainPlayer+': </td><TD width=250><INPUT type=submit id=pbResDo value="'+culang.buttonRessourceAccept+'">\
			&nbsp; <SPAN id=pbResNone class=boldRed></span></td></tr></table><TABLE class=pdxTab><TR valign=top><TD>\
			<INPUT id=pbResButAll type=submit value="'+culang.mainAll+'" style="width:100%; margin-bottom:5px"><BR><INPUT id=pbResButNone type=submit value="'+culang.mainNone+'"></td>\
			<TD width=10></td><TD><TABLE cellpadding=0 cellspacing=0 class=ksTabLined>\
			<TBODY id=pbResTbody style="width: 400px; overflow:auto; display:block;">\
			<TR style="font-weight:bold; background:white"><TD><b><u>'+culang.mainName+'</u></b></td><TD><b><u>'+uW.g_js_strings.commonstr.might+'</u></b></td><TD width=20></td></tr>';
			for (var i=0; i<t.users.length; i++){
				m += '<TR><TD><INPUT type=checkbox id=pbrchk_'+ i +'> &nbsp;'+ t.users[i].name +'</td><TD>'+ t.users[i].might +'</td></tr>';
			}
			ById('resDiv').innerHTML = m + '</tbody></table></td></tr></center></table>';
			new CdispCityPicker ('pbrescitysel', ById('pbrescityselspan'), true, t.e_CityButton, t.city.idx);
			ById('pbResDo').addEventListener ('click', t.getErDone, false);
			ById('pbResButAll').addEventListener ('click', t.e_butAll, false);
			ById('pbResButNone').addEventListener ('click', t.e_butNone, false);
			// var tbody = ById('pbResTbody');
			// tbodyScroller (tbody, getRemainingHeight (tbody, mainPop.div));
		}
	},

	e_CityButton : function (city, x, y){
		var t = Tabs2.Resources;
		t.city = city;
	},

	e_butAll : function (){
		var t = Tabs2.Resources;
		for (var i=0; i<t.users.length; i++)
			ById('pbrchk_'+i).checked = true;
	},

	e_butNone : function (){
		var t = Tabs2.Resources;
		for (var i=0; i<t.users.length; i++)
			ById('pbrchk_'+i).checked = false;
	},

	getErDone : function (){
		var t = Tabs2.Resources;
		t.doList = [];
		ById('pbResNone').innerHTML = '';
		Options.getResType = ById('pbResColType').value;
		t.total = {gold:0, 1:0, 2:0, 3:0, 4:0};
		for (var i=0; i<t.users.length; i++){
			if (ById('pbrchk_'+i).checked)
				t.doList.push (t.users[i]);
		}
		if (t.doList.length==0){
			ById('pbResNone').innerHTML = ''+culang.ressourceNoneSelected+'';
			return;
		}
		t.accepting = true;
		ById('pballlist').value = ''+culang.ressourceAcceptStop+'';
		ById('resDiv').innerHTML = '<DIV id=rsltDiv style="text-align: center;"><div class="pdxStat">'+culang.ressourceAcceptNow+' <u>'+ t.doList.length +'</u> '+culang.ressourceAcceptNow2+'</div><BR></div>';
		t.acceptNext ();
	},


	allDone : function (msg){
		var t = Tabs2.Resources;
		msg += ''+uW.g_js_strings.commonstr.gold+': '+addCommas(t.total.gold)+'<BR>';
		for(var i=1; i<=4; i++){
			msg += t.resource[i]+': '+addCommas(t.total[i])+'<BR>';
		}
		ById('rsltDiv').innerHTML += '<BR>' + msg;
		ById('pballlist').value = ''+uW.g_js_strings.commonstr.alliance+'';
		t.accepting = false;
	},


	acceptNext : function (){
		var t = Tabs2.Resources;
		var gift = t.doList.shift();
		if (gift == null){
			t.allDone ('<div class=pdxStat>'+culang.ressourceAcceptHead+'</div>');
			return;
		}
		var acpDiv = ById('rsltDiv');
		var curDiv = document.createElement ('div');
		acpDiv.appendChild (curDiv);
		curDiv.innerHTML = '<i><u>'+culang.mainFrom+'</u></i> <span class="boldGreen">'+ gift.name +'</span>: ';
		var statSpan = document.createElement ('span');
		curDiv.appendChild (statSpan);
		statSpan.innerHTML = ' ';
		t.getCourtAction (gift, gotGiftData);

		function gotGiftData (rslt){
			if (!t.accepting)
				return;
			if (rslt.ok){
				var msg = rslt.gold +' '+uW.g_js_strings.commonstr.gold+' '+culang.mainAnd+' '+rslt.resource +' '+ t.resource[rslt.resourcetype]+' ...<b>'+culang.mainOK+'</b>.';
				statSpan.innerHTML += msg;
				t.total.gold += rslt.gold;
				t.total[rslt.resourcetype] += rslt.resource;
				t.acceptNext ();
				return;
			}

			if (rslt.msg)
				msg = '<B>'+ rslt.msg + '</b>';
			else
				msg = '<SPAN class=boldRed>'+culang.mainError+': '+ rslt.ajaxErr +'</span>';

			curDiv.removeChild (statSpan);
			curDiv = document.createElement ('div');
			curDiv.className = 'indent25';
			acpDiv.appendChild (curDiv);
			curDiv.innerHTML = msg;
			t.acceptNext ();
		}

	},

	getMembersInfo : function (pageNo, notify) {
		var t = Tabs2.Resources;
		var params = uW.Object.clone(uW.g_ajaxparams);

		params.pageNo = pageNo;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/allianceGetMembersInfo.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				notify (rslt);
			},
			onFailure: function (rslt) {
				notify ({errMsg:'Ajax Comm Error'});
			},
		});
	},
	getFriendsInfo : function (notify) {
		var t = Tabs2.Resources;
		var params = uW.Object.clone(uW.g_ajaxparams);
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/getAppFriends.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				notify (rslt);
			},
			onFailure: function (rslt) {
				notify ({errMsg:'Ajax Comm Error'});
			},
		});
	},
	getDailyAction : function (uid, notify){
		var t = Tabs2.Resources;
		var params = uW.Object.clone(uW.g_ajaxparams);

		params.pid = uid;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/viewCourt.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				notify (rslt);
			},
			onFailure: function (rslt) {
				notify ({errMsg:'Ajax Comm Error'});
			},
		});
	},

	getCourtAction : function (gift, notify){
		var t = Tabs2.Resources;
		var params = uW.Object.clone(uW.g_ajaxparams);

		params.atype = Options.getResType;
		params.toid = gift.userId;
		params.givercityid = t.city.id;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/courtDoAction.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				notify (rslt);
			},
			onFailure: function (rslt) {
				notify ({errMsg:'Ajax Comm Error'});
			},
		});
	},

	checkDailyAction : function (userList, notify){
		var t = Tabs2.Resources;
		var count = 0;
		t.getDailyAction(userList[count].userId, parseViewCourt);

		function parseViewCourt (rslt){
			if (!rslt.ok || rslt.errMsg)
				notify ({errMsg:'Ajax Comm Error'});
			if(rslt.dailyActionFlag == 0)
				t.users.push(userList[count]);
			t.progress(count, 'pbResUserAvailCount');
			count++;
			if(count < userList.length){
				t.getDailyAction(userList[count].userId, parseViewCourt);
			} else {
				notify();
			}
		}
	},
	fetchUserList : function (tt, notify){
		var t = Tabs2.Resources;
		var userList = [];
		if (tt==1)
			t.getMembersInfo(1, parseAlliancePage);

		if (tt==2)
			t.getFriendsInfo(parseAlliancePage2);
		function parseAlliancePage (rslt){
			if (!rslt.ok || rslt.errMsg)
				notify ({errMsg:'Ajax Comm Error'});
			var users = rslt.memberInfo;
			for(var k in users){
				userList.push({userId:users[k].userId, name:users[k].name, might:users[k].prestige, type:'alliance'});
			}
			t.progress(userList.length, 'pbResUserListCount');
			if(rslt.currentPage < rslt.noOfPages){
				t.getMembersInfo((rslt.currentPage+1), parseAlliancePage);
			} else {
				notify(userList);
				//t.getFriendsInfo(parseAlliancePage2);
			}
		}


		function parseAlliancePage2 (rslt){
			if (!rslt.ok || rslt.errMsg)
				notify ({errMsg:'Ajax Comm Error'});
			var users = rslt.data;
			for(var k in users){
				if (users[k].userId!=undefined)
					userList.push({userId:users[k].userId, name:users[k].displayName, might:users[k].might, type:'friends'});
			}
			t.progress(userList.length, 'pbResUserListCount');
			notify(userList);
		}

	},
	getContent : function (){
		var t = Tabs2.Resources;
		return t.cont;
	},
},
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Ascension.js">
//	
//	   KOC POWER - TABS2 ASCENSION										        
//	
 

Tabs2.Ascension = {
	myDiv : null,
	cont : null,

	init : function (){
		this.myDiv = document.createElement('div');
		return this.myDiv;
	},

	hide : function (){
		var t = Tabs2.Ascension;

	},
	getContent : function (){
		return Tabs2.Ascension.myDiv;
	},

	show : function (){
		var t = Tabs2.Ascension;
		t.cont = this.myDiv;
		var m="";

        m += '<DIV class=pdxStat id=pbAscensionMain>'+culang.ascensionHead+'</div><TABLE id=pbAscension><TR>';
        m += '<TD></td><TD><b><u>'+culang.ascensionPercent+'</u></b></td><TD><CENTER><b><u>'+culang.ascensionMenu+'</u></b></center></td><TD><b><u>'+culang.ascensionCurrentLevel+'</u></b></td><TD><b><u>'+culang.ascensionCurrentCost+'</u></b></td><TD><input value="'+culang.ascensionBuildingValues+'" type=submit id="pbBuildingValues" ></td><TR>';
        for (i = 0; i < Cities.cities.length; i++) {
            var cityPrestige = Seed.cityData.city[Cities.cities[i].id].cityValue;
            var cityPrestigeLevel = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeLevel;
            var isPrestigeCity = Seed.cityData.city[Cities.cities[i].id].isPrestigeCity;
            var currentGemPrice = null;
            var fullPrestige = 1200;
            var progressWidth = parseInt(((cityPrestige / fullPrestige) * 100));
            if (progressWidth > 100) progressWidth = 100;
            var fullBarWidth = 378;
            var gemFullPrice = 1250;
            m += '<TR><TD>'+culang.kocCity+' ' + Cities.cities[i].name + ' - </td>';
            m += '<TR><TD background="'+IMGprogressBarBrown+'" width=' + fullBarWidth + ' height=25">';
            m += '<DIV id=pbGreenBar_' + i + '></div></td><TD align=center><DIV id=pbProgPerc_' + i + '></div></td><TD><INPUT id=pbAscendBtn_' + Cities.cities[i].id + ' type=submit class=pbButton value="'+culang.ascensionAscend+'"></td><TD align=center><DIV id=pbCityPrestigeLevel_' + i + '></div></td><TD align=center><DIV id=pbGemCost_' + Cities.cities[i].id + '></div></td><TD align=center><CENTER><DIV id=pbAscCurMight_'+i+'></div></center></td>';
  
  }
		t.cont.innerHTML = m;
		
		Tabs2.Ascension.Timer = setInterval(Tabs2.Ascension.paintTab, 1000)
        for (i = 0; i < Cities.cities.length; i++) {
            document.getElementById('pbAscendBtn_' + Cities.cities[i].id).addEventListener('click', function () {
                var t = Tabs2.Ascension
                var what = this.id.substr(12); // strip first 12 char's -> pbAscendBtn_
                t.clickCitySelect(what);
            });
            var isPrestigeCity = Seed.cityData.city[Cities.cities[i].id].isPrestigeCity;
            if (isPrestigeCity) {
                t.getGemCost(Cities.cities[i].id, function (cid, cost, origCost) {
                    if (cost < 0 || cost == null || origCost == null) {
                        document.getElementById('pbGemCost_' + cid).innerHTML = '<CENTER>'+culang.buttonMax+'</center>';
                    } else {
                        document.getElementById('pbGemCost_' + cid).innerHTML = '<CENTER>' + cost + '/' + origCost + '</center>';
                    }
                })
            } else {
                document.getElementById('pbGemCost_' + Cities.cities[i].id).innerHTML = '<CENTER><i>'+culang.ascensionNotAscended+'</i></center>';
            }
        }
	
		
        document.getElementById('pbBuildingValues').addEventListener('click', function(){t.paintHelp();});

     
			// ById('KsFiltre8ST').value=t.filtre8;
			// ById('KsFiltre8ST').addEventListener ('click', t.filtreaction, false);


},
		
		
 paintHelp: function() {
    	var t = Tabs2.Ascension;
    	var helpText = culang.ascensionHelpPop;
       	var pop = new CPopup ('ascensionHelp', 0, 0, 400, 400, true);
       	pop.centerMe (mainPop.getMainDiv());  
       	pop.getMainDiv().innerHTML = helpText;
       	pop.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.ascensionHeadHelpPop+'</DIV>';
       	pop.show (true);
    },
    paintTab: function () {
        for (i = 0; i < Cities.cities.length; i++) {
            var cityPrestige = Seed.cityData.city[Cities.cities[i].id].cityValue;
            var cityPrestigeLevel = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeLevel;
            var isPrestigeCity = Seed.cityData.city[Cities.cities[i].id].isPrestigeCity;
            var currentGemPrice = null;
            var fullPrestige = 1200;
            var progressWidth = parseInt(((cityPrestige / fullPrestige) * 100));
            if (progressWidth > 100) progressWidth = 100;
            var fullBarWidth = 378;
            var gemFullPrice = 1250;
            m += '<TR><TD>City ' + Cities.cities[i].name + ' - </td>';
            m += '<TR><TD style="background:'+IMGprogressBarBrown+'" width=100% height=25">';
            if (isPrestigeCity) {
                if (cityPrestigeLevel < 3) {
                    document.getElementById('pbGreenBar_' + i).innerHTML = '<img src="'+IMGprogressBarGreen+'" width=' + progressWidth + '% height=25>'
                    document.getElementById('pbProgPerc_' + i).innerHTML = progressWidth + '%';
                    document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = cityPrestigeLevel + '/3';
                    document.getElementById('pbAscCurMight_'+i).innerHTML = cityPrestige + '/1200';
                } else {
                    document.getElementById('pbGreenBar_' + i).innerHTML = '<CENTER>'+culang.ascensionComplete+'</center>'
                    document.getElementById('pbProgPerc_' + i).innerHTML = 'N/A';
                    document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = 'N/A';
                    document.getElementById('pbAscCurMight_' + i).innerHTML = 'N/A';
                }
                m += '<TR>';
            } else {
                document.getElementById('pbGreenBar_' + i).innerHTML = '<CENTER>'+culang.ascensionNotComplete+'</center>'
                document.getElementById('pbProgPerc_' + i).innerHTML = '<CENTER>N/A</center>';
                document.getElementById('pbCityPrestigeLevel_' + i).innerHTML = '<CENTER>0/3</center>';
                document.getElementById('pbAscCurMight_' + i).innerHTML = 'N/A';
            }
        }
    },
    clickCitySelect: function (city) {
        var t = Tabs2.Ascension;
        t.selectedCity = city;
        t.JumpCity(city);
        uW.cm.PrestigeManagerController.open()
    },
    JumpCity: function (city) {
       var t = Tabs2.Ascension;
        for (i = 0; i < Seed.cities.length; i++) {
            if (Seed.cities[i][0] == city) var cityNum = i;
        }
        cityNum++;
        var obj = document.getElementById('citysel_' + cityNum);
        return t.ClickWin(window, obj, 'click');
    },
    ClickWin: function (win, obj, evtName) {
        var evt = win.document.createEvent("MouseEvents");
        evt.initMouseEvent(evtName, true, true, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        return !obj.dispatchEvent(evt);
    },
    getGemCost: function (cityId, callback) {
       var t = Tabs2.Ascension;
        var isPrestigeCity = Seed.cityData.city[cityId].isPrestigeCity;
        var cityPrestigeLevel = Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeLevel;
        if (isPrestigeCity && cityPrestigeLevel < 3) {
            var params = uW.Object.clone(uW.g_ajaxparams);
            params.cid = cityId;
            params.prestigeType = 1;
             
            new MyAjaxRequest(uW.g_ajaxpath + "ajax/getPrestigeCost.php" + uW.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if (rslt.ok) {
                        callback(cityId, rslt.cost, rslt.original_cost)
                    }
                }
            });
        } else {
            callback(cityId, null, null)
        }
    },

    hide: function () {clearInterval(Tabs2.Ascension.Timer) },

}
//</editor-fold>
 

//<editor-fold desc="SPLIT:Tabs/Throne.js">
//	
//	   KOC POWER - TABS THRONE										        
//	
Tabs.Throne = {
	tabOrder: TabOptions.toThrone,
	tabLabel: culang.tabLabelThrone,
	myDiv : null,
	cont : null,
	passage:null,
	timer : null,
	filtre:"",
	tableau:[],
	filtre2:"",
	filtre3:"",
	filtre6:0,
	filtre7:false,
	filtre8:"",
	filtre4:Options.AllEffet,
	filtre5:Options.EffetRouge,
	init : function (div){
		var t = Tabs.Throne;
		t.cont = div;	
	},

	hide : function (){
		var t = Tabs.Throne;

	},
	getContent : function (){
		return Tabs.Throne.myDiv;
	},

	show : function (){
		var t = Tabs.Throne;
		if (Options.salvageconfig.CityCity==undefined) Options.salvageconfig.CityCity=0;
		uW.Kssalvage=t.salvage;
		uW.KsequipItem=t.equipItem;
		uW.KsUnequipItem=t.UnequipItem;
		uW.KsRepair = t.Repair;
		uW.KsupgradeQualite = t.upgradeQualite;
		uW.KsupgradeLevel = t.upgradeLevel;
		var m="";
		var nb=0;
		var nbbroken=0;
		var k=Seed.throne.slotEquip[Seed.throne.activeSlot];
		var item;
		var faction;
		var items = uW.kocThroneItems;
		var sl=0;
		if (t.passage==null) {
			t.passage=1;
			var taille = 500; //uW.screen.height - mainPop2.getLocation().y - 450;
			m += '<DIV class=pdxStat>'+culang.throneHead+'</div><table style="background-color:transparent;max-width:100%;width:755px;" cellspacing=0 cellpadding=2><tr>\
         <td><input type=checkbox id=KsFiltre4ST> '+culang.throneShowAllEffect+' &nbsp;<input type=checkbox id=KsFiltre7ST> '+culang.throneRepairItems+' - '+culang.throneRedEffects+' <select id=Kslisteeffets></select>\
         <br>'+culang.throneUseAehterstones+' <span id=KsTroneCityCity></span>&nbsp;<span id=KsTroneCityCityS>\
         </tr></table>';
			m +='<DIV class=pdxStat>'+culang.throneQualityUpgradeNote2+'</div><DIV id=KsTroneAether style="width:100%;height:45px;max-height:45px;"></DIV><DIV class=pdxStat>'+culang.throneHeadEquippedItems+'</div><DIV id=KsTroneE style="width:100%;height:33px;max-height:33px;"></DIV><DIV class=pdxStat><span id=KsNbArticle></span></div><center><table style="background-color:transparent;max-width:95%;width:755px;" cellspacing=0 cellpadding=2>\
      <tr><td colspan=1 width=35>&nbsp;</td>\
      <td width=35><select id=KsFiltre8ST><option value="">-- '+culang.throneLevel+' --</option><option value=0>+0</option><option value=1>+1</option><option value=2>+2</option><option value=3>+3</option><option value=4>+4</option><option value=5>+5</option><option value=6>+6</option><option value=7>+7</option><option value=8>+8</option><option value=9>+9</option><option value=10>+10</option><option value=11>+11</option><option value=12>+12</option><option value=13>+13</option><option value=14>+14</option></select></td>\
      <td width=120><select id=KsFiltre2ST><option value="">-- '+culang.throneQuality+' --</option><option value="0">'+uW.g_js_strings.throneRoom.simple+'</option><option value="1">'+uW.g_js_strings.throneRoom.common+'</option><option value="2">'+uW.g_js_strings.throneRoom.uncommon+'</option><option value="3">'+uW.g_js_strings.throneRoom.rare+'</option><option value="4">'+uW.g_js_strings.throneRoom.epic+'</option><option value="5">'+uW.g_js_strings.throneRoom.wondrous+'</option><option value="6">'+uW.g_js_strings.throneRoom.unique+'</option></select></td>\
      <td width=80><select id=KsFiltreST><option value="">-- '+culang.throneFamily+' --</option><option value="briton">briton</option><option value="druid">druid</option><option value="fey">fey</option></select></td>\
      <td width=80><select id=KsFiltre3ST><option value="">-- '+culang.throneType+' --</option><option value="advisor">advisor</option><option value="banner">banner</option><option value="chair">chair</option><option value="table">table</option><option value="window">window</option><option value="trophy">thropy</option><option value="candelabrum">candelabrum</option><option value="hero">hero</option></select></td>\
      <td width=250><select id=KsFiltre5ST></select></td>\
      <td width=80><input type=checkbox id=KsTroneInverse>'+culang.throneInvertOrder+'</td></tr></table><DIV id=KsTroneC style="width:100%;height:'+taille+'px; max-height:'+taille+'px; overflow-y:auto"></div><br>';
			t.cont.innerHTML = m;

			var dcp0 = new CdispCityPicker ('KsRCityC', ById('KsTroneCityCity'), false, function(c) { ById('KsTroneCityCityS').innerHTML=c.name;var t = Tabs.Throne;Options.salvageconfig.CityCity=c.idx;saveOptions();t.show();}, Options.salvageconfig.CityCity);


			var liste = uW.cm.thronestats.effects;
			ById("Kslisteeffets").innerHTML="";
			var o = document.createElement("option");
			o.text = "-- "+culang.mainNone+" --";
			o.value = 0;
			ById("Kslisteeffets").options.add(o);
			for (k in liste){
				if (liste[k] !=undefined){
					var o = document.createElement("option");
					o.text = liste[k][1];
					o.value = k;
					ById("Kslisteeffets").options.add(o);
				}
			}
			ById("KsFiltre5ST").innerHTML="";
			var o = document.createElement("option");
			o.text = "-- "+culang.throneBonus+" --";
			o.value = 0;
			ById("KsFiltre5ST").options.add(o);
			for (k in liste){
				if (liste[k] !=undefined){
					var o = document.createElement("option");
					o.text = liste[k][1];
					o.value = k;
					ById("KsFiltre5ST").options.add(o);
				}
			}
			ById('Kslisteeffets').value=t.filtre5;
			ById("Kslisteeffets").addEventListener ('change', t.filtreaction, false);

			ById('KsFiltreST').value=t.filtre;
			ById('KsFiltreST').addEventListener ('change', t.filtreaction, false);
			ById('KsFiltre2ST').value=t.filtre2;
			ById('KsFiltre2ST').addEventListener ('change', t.filtreaction, false);
			ById('KsFiltre3ST').value=t.filtre3;
			ById('KsFiltre3ST').addEventListener ('change', t.filtreaction, false);
			ById('KsFiltre4ST').checked=t.filtre4;
			ById('KsFiltre4ST').addEventListener ('click', t.filtreaction, false);
			ById('KsFiltre5ST').value=t.filtre6;
			ById('KsFiltre5ST').addEventListener ('change', t.filtreaction, false);

			ById('KsFiltre7ST').checked=t.filtre7;
			ById('KsFiltre7ST').addEventListener ('click', t.filtreaction, false);
			ById('KsFiltre8ST').value=t.filtre8;
			ById('KsFiltre8ST').addEventListener ('click', t.filtreaction, false);

			ById('KsTroneInverse').checked=Options.TroneInverse;
			ById('KsTroneInverse').addEventListener ('click', function() {
				Options.TroneInverse = ById('KsTroneInverse').checked;

				saveOptions ();
				t.show();
			}, false);

		}
		m='<table style="background-color:transparent;width:755px;max-width:95%;" cellspacing=0 cellpadding=2>';
		t.tableau=[];
		for (var z in items) {
			if (items[z].id) {
				item=uW.kocThroneItems[items[z].id];
				if (item) {

					t.tableau[sl]=items[z].id;
					sl++
				}
			}
		}
		var lignauto = Seed.throne.rowNum * 5;
		if (Options.TroneInverse) t.tableau.reverse();
		var pastoucher = [];

		for (var nbslot=1;nbslot<=Seed.throne.slotNum;nbslot++) {
			B = Seed.throne.slotEquip[nbslot];
			for (var zzz in B) {
				if (uW.kocThroneItems[B[zzz]]) {
					pastoucher.push(B[zzz]);
				}
			}
		}

		var nbl=t.tableau.length+1;

		var KstimeLeft=-1;
		if (Seed.queue_throne) {
			if (Seed.queue_throne.end)
				KstimeLeft = Seed.queue_throne.end - uW.unixtime();
		}

		for (var z=0;z<t.tableau.length;z++) {
			item=uW.kocThroneItems[t.tableau[z]];
			itemNr=0; 
			for(z2 in uW.kocThroneItems) {
				itemNr++;
				if(z2==item.id)break;
			}
			nb++
			faction=item.faction;
			x=0;
			nbl--;
			if ( (t.filtre=="" || t.filtre==faction) && 
					 (t.filtre2=="" || t.filtre2==item.quality) && 
					 (t.filtre3=="" || t.filtre3==item.type) && 
					 (t.filtre7==false || (t.filtre7==item.isBroken || (t.filtre=true && Seed.queue_throne.itemId==item.id)))  && 
					 (t.filtre8=="" || t.filtre8==item.level)   )  {

				var ok=0;
				for (var u in item.effects) {
					if (t.filtre6==item.effects[u].id) {
						ok=1;
					}
				}

				if (t.filtre6=="0" || ok==1) {
					var styleez="";

					if (item.isEquipped) {
						equip="equip";
						styleez="background-color:#DC9999";
					}else{
						equip="normal";
					}

					if (pastoucher.toString().indexOf(t.tableau[z])>-1 && equip=="normal")
						styleez="background-color:#99DC99";

					var styleauto="";
					//if (upgradeData.item_upgrade[t.tableau[z]] || upgradeData.item_enhance[t.tableau[z]]) {
					//       styleauto="background-color:#D9D988";
					//       m+="<tr><td style='"+styleauto+";width:35px' title='En auto upgrade'>"
					//      }else {
					m+="<tr><td style='"+styleez+";width:35px'>"
					//      }
					if (Seed.queue_throne) {
						if (Seed.queue_throne.itemId==item.id) {
							nbbroken++
							m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/sm_hammer.png>";
						} else {
							if (item.isBroken) {
								nbbroken++
								m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/sm_fail_overlay.png>";
							} else {
								m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+ faction+"/"+ faction+"_"+item.type+"_"+equip+"_1_5.png>";
							}
						}
					} else {
						if (item.isBroken) {
							m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/sm_fail_overlay.png>";
						} else {
							m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+ faction+"/"+ faction+"_"+item.type+"_"+equip+"_1_5.png>";
						}
					}
					m+="</td>"
					
					m+="<td colspan=4 style='"+styleez+";width:250px'>";
					m+=getThroneItemName(item.id)+"<br>";
					m+="#"+itemNr+" / "+item.faction+" / "+item.type;
					m+="</td>";
					//<td style='"+styleez+";width:120px'>"+ item.createPrefix() + "</td><td style='"+styleez+";width:80px'>"+item.faction+"</td><td style='"+styleez+";width:80px'> "+item.type+"</td>";

					m+="<td style='"+styleez+";width:300px'>";
					for (var u in item.effects) {
						x++;
						L = item.effects[u];
						if ((item.quality >= x && !t.filtre4) || t.filtre4) {
							var coleur="";
							var stylee="";
							if (item.quality < x)
								stylee="text-decoration:line-through";
							if (t.filtre5==item.effects[u].id) stylee+=";color:#AA1111;font-weigth:bold";
							effect = uW.cm.thronestats.effects[L.id];
							var id = L.id;
							var tier = L.tier;
							p = false;
								while (!p && (tier > -1)) {
								p = uW.cm.thronestats.tiers[id][tier];
								tier--;
							}
							var base = p.base || 0;
							var growth = p.growth ||0;
							var percent = + base + (item.level * item.level + item.level) * + growth * 0.5;
							//percent = percent > 0 ? "+" + percent : + percent;
							percent = Math.round(percent*100)/100;
							typpee="";
							for (l=0;l<effect["2"].length;l++){
								typpee+=effect["2"][l];
							}
							m+="<span style='"+stylee+"'><font color="+coleur+">" + percent + "% " + effect[1] + " ("+typpee+")</font></span><bR>";
						}
					}

					if ((Options.TroneInverse && nbl<=lignauto) || (!Options.TroneInverse && nb<=lignauto)) {
						m+="</td><td style='"+styleez+"'><center>";

						if (Seed.queue_throne && Seed.queue_throne.itemId==item.id) {
							var timeLeft = Seed.queue_throne.end - uW.unixtime();
							if (timeLeft<0) {
								m+=""+culang.throneRepairDone+"</td></tr>";
							} else {
								m+=""+culang.throneRepairTime+"<br>"+timestr(timeLeft)+"";
							}
						}else{
							if (item.isBroken) {
								if (KstimeLeft<0) {
									m+="<a onclick='KsRepair("+t.tableau[z]+")' class='buttonv2 h20 blue'>"+culang.throneRepair+"</a>";
								}

							} else {
								if (item.quality<5) {
									stoneenhance=uW.cm.thronestats["enhance"][item.quality+1].Stones;
									cityId='city'+Seed.cities[Options.salvageconfig.CityCity][0];
									if (parseIntNan(stoneenhance)<parseIntNan(Seed.resources[cityId]['rec5'][0])) {
										m+="<a onclick='KsupgradeQualite("+t.tableau[z]+")' class='buttonv2 h20 brown'  title='"+culang.throneQualityUpgradeNote+" "+stoneenhance+" "+culang.throneQualityUpgradeNote2+"'>+"+culang.throneQuality+"</a>";
									} else {
										//m+="<a class='buttonv2 h20 red' title='Besoin de "+stoneenhance+" pierres ether'>+Qualit&eacute;</a>";
									}
								}
								if (item.level<15) {
									stoneupgrade=uW.cm.thronestats["upgrade"][item.level+1].Stones;
									cityId='city'+Seed.cities[Options.salvageconfig.CityCity][0];
									if (parseIntNan(stoneupgrade)<parseIntNan(Seed.resources[cityId]['rec5'][0])) {
										m+="<a onclick='KsupgradeLevel("+t.tableau[z]+")' class='buttonv2 h20 brown' title='"+culang.throneQualityUpgradeNote+" "+stoneupgrade+" "+culang.throneQualityUpgradeNote2+"'>+"+culang.throneLevel+"</a>";
									}else{
										//m+="<a class='buttonv2 h20 red' title='Besoin de "+stoneenhance+" pierres ether'>+Niveau</a>";
									}
								}
								m+="<br><a onclick='Kssalvage("+t.tableau[z]+")' class='buttonv2 h20 red'>"+culang.mainDelete+"</a>";
								if (equip=="normal")
									m+="<a onclick='KsequipItem("+t.tableau[z]+")' class='buttonv2 h20 blue'>"+culang.throneEquipItem+"</a>";
								else
									m+="<a onclick='KsUnequipItem("+t.tableau[z]+")' class='buttonv2 h20 blue'>"+culang.throneUnequipItem+"</a>";
							} // fin de isbroken
						}
					} else {
						m+="</td><td style="+styleez+"><center><items><b>"+culang.throneNoSlots+"";
					}
					m+"</td></tr>";
				}
			}

		}
		ById("KsTroneC").innerHTML=m;
		// Equipement
		var effft="",faction={0:'advisor',1:'banner',2:'chair',3:'table',4:'window',5:'trophy',6:'candelabrum',7:'hero'};
		var zz="<center><table width=100%><tr>";
		for (var fp in faction) {
			equip="normal";
			effft="";
			var k=Seed.throne.slotEquip[Seed.throne.activeSlot];
			for (var tt in k) {
				if (uW.kocThroneItems[k[tt]])
					if (uW.kocThroneItems[k[tt]].type==faction[fp]) {
						var fr = uW.kocThroneItems[k[tt]].faction;
						equip="normal";
						x=0;
						for (var u in uW.kocThroneItems[k[tt]].effects) {
							x++;
							if (uW.kocThroneItems[k[tt]].quality >= x) {
								var id = uW.kocThroneItems[k[tt]].effects[u].id;
								var tier = uW.kocThroneItems[k[tt]].effects[u].tier;
								p = false;
								while (!p && (tier > -1)) {
									p = uW.cm.thronestats.tiers[id][tier];
									tier--;
								}
								var base = p.base || 0;
								var growth = p.growth ||0;
								var pourc = + base + (uW.kocThroneItems[k[tt]].level * uW.kocThroneItems[k[tt]].level + uW.kocThroneItems[k[tt]].level) * + growth * 0.5;
								pourc = Math.ceil(pourc);
								effft+= pourc + "% " + uW.cm.thronestats.effects[uW.kocThroneItems[k[tt]].effects[u].id][1]+ "&#013;";

							}
						}
					}
			}
			zz+="<td width=30><img title='"+effft+"' align=absmiddle width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+fr+"/"+fr+"_"+faction[fp]+"_"+equip+"_1_5.png><td>"+faction[fp]+"</td>";
		}
		zz+="</tr></table>";
		ById("KsTroneE").innerHTML=zz;
		ById("KsNbArticle").innerHTML= nb + " "+culang.throneHeadEquippedItems2+" "+ nbbroken +" "+culang.throneHeadEquippedItems3+"";
		clearTimeout(t.citystattimer);
		t.citystat();
	},
	citystattimer:null,
	citystat:function() {
		var t = Tabs.Throne;
		var zz="<TABLE class=ptTabLined cellspacing=0 style='margin-bottom:5px;'><tr><td></td>";
		var zx="";
		clearTimeout(t.citystattimer);
		for(var i=0; i<Cities.numCities; i++) {
			var cityID = 'city'+ Cities.cities[i].id;
			zz += "<TD width=81 align=center><B>"+ Cities.cities[i].name.substring(0,10) +'</b></td>';
			zx += "<TD width=81 align=center><B>"+ addCommas(parseIntNan(Seed.resources[cityID]['rec5'][0])) + "</b></td>";
		}
		zz+="</tr><tr><td><img height=18 src='"+IMGastone30+"'></td>"+zx;
		zz+="</table>";

		ById("KsTroneAether").innerHTML=zz;
		t.citystattimer=setTimeout(t.citystat,5000);

	},
	filtreaction: function() {
		var t = Tabs.Throne;
		t.filtre = ById('KsFiltreST').value;
		t.filtre2 = ById('KsFiltre2ST').value;
		t.filtre3 = ById('KsFiltre3ST').value;
		t.filtre4 = ById('KsFiltre4ST').checked;
		t.filtre5 = ById('Kslisteeffets').value;
		t.filtre6 = ById('KsFiltre5ST').value;
		t.filtre7 = ById('KsFiltre7ST').checked;
		t.filtre8 = ById('KsFiltre8ST').value;
		Options.EffetRouge = t.filtre5;
		Options.AllEffet = t.filtre4;
		saveOptions ();
		t.show();

	},
	upgradeQualite:function(id) {
		var t = Tabs.Throne;

		var currentcityid = Seed.cities[Options.salvageconfig.CityCity][0];

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="upgradeQuality";
		params.ctrl="throneRoom\\ThroneRoomServiceAjax";
		params.throneRoomItemId=id;
		params.buffItemId=0;
		params.payment="aetherstone";
		params.cityId=currentcityid;
		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok === true){
					Seed.resources["city" + currentcityid].rec5[0] = Seed.resources["city" + currentcityid].rec5[0] - m.aetherstones;

					var s = uW.kocThroneItems[id];
					if (m.success) {
						s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
					} else {
						s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
						if (m.break) { s.brokenType = "quality"; }
						s.isBroken = true;
						s.name = s.createName();
					}
					t.show();
				}
			}
		});

	},
	upgradeLevel:function(id) {
		var t = Tabs.Throne;
		var currentcityid = Seed.cities[Options.salvageconfig.CityCity][0];

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="upgradeLevel";
		params.ctrl="throneRoom\\ThroneRoomServiceAjax";
		params.throneRoomItemId=id;
		params.buffItemId=0;
		params.payment="aetherstone";
		params.cityId=currentcityid;
		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok === true){
					Seed.resources["city" + currentcityid].rec5[0] = Seed.resources["city" + currentcityid].rec5[0] - m.aetherstones;
					var s = uW.kocThroneItems[id];
					if (m.success) {
						s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
					} else {
						s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
						if (m.break) { s.brokenType = "level"; }
						s.isBroken = true;
						s.name = s.createName();
					}
					t.show();
				}
			}
		});

	},
	Repair:function(id) {
		var t = Tabs.Throne;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="timeRepair";
		params.ctrl="throneRoom\\ThroneRoomServiceAjax";
		params.throneRoomItemId=id;
		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok === true){
					Seed.queue_throne.start = uW.unixtime();
					Seed.queue_throne.end = m.eta;
					Seed.queue_throne.itemId = id;
					uW.kocThroneItems[id].isBroken = false;
					uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
					t.show();
				}
			}
		});

	},
	equipItem: function(id) {
		var t = Tabs.Throne;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="equipItem";
		params.ctrl="throneRoom\\ThroneRoomServiceAjax";
		params.itemId=id;
		params.presetId=Seed.throne.activeSlot;
		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok === true){
					uW.cm.ThroneView.clickItemEquip(uW.kocThroneItems[id]);
					t.show();
				}
			}
		});
	},
	UnequipItem: function(id) {
		var t = Tabs.Throne;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="unequipItem";
		params.ctrl="throneRoom\\ThroneRoomServiceAjax";
		params.itemId=id;
		params.presetId=Seed.throne.activeSlot;
		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok === true){
					uW.cm.ThroneView.clickItemUnequip(uW.kocThroneItems[id]);
					t.show();
				}
			}
		});
	},
	salvage: function(id) {
		var t = Tabs.Throne;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="salvage";
		params.ctrl="throneRoom\\ThroneRoomServiceAjax";
		params.itemId=id;
		/*var cityid = 0;
		 for (var k in Cities.byID) {
		 if (Seed.resources["city"+k]["rec5"][0] < 1000000)
		 {
		 cityid = k;
		 break;
		 }
		 }
		 if (cityid == 0) cityid = Seed.cities[0][0];*/
		params.cityId=Seed.cities[Options.salvageconfig.CityCity][0];

		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok){

					uW.kocThroneItems[id].salvage();
					t.show();
				}else{

				}
			}
		});
	}
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Overview.js">
//	
//	   KOC POWER - TABS OVERVIEW										        
//	
 

function getRallypointInfo(cityId) {
	var ret = {
		level: 0,
		maxMarches: 0,
		maxMarchSize: 0,
		maxMarchSize25: 0,
		maxMarchSize50: 0,
		usedSlots: 0,
		freeSlots: 0,
	};
	var city = 'city'+ cityId;
	for (var o in Seed.buildings[city]) {
		var buildingType = parseInt(Seed.buildings[city][o][0]);
		var buildingLevel = parseInt(Seed.buildings[city][o][1]);
		if (buildingType == 12) {
			ret.level = parseInt(buildingLevel);
			if (parseInt(buildingLevel) == 12) {
				ret.maxMarches = 11;
			} else {
				ret.maxMarches = parseInt(buildingLevel);
			}
			if (uW.cm.PrestigeModel.isPrestige(cityId)) {
				var a = uW.cm.PrestigeModel.getPrestigeLevel(cityId);
				if (a > 0) {
					var mm = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
					k = uW.JSON.parse(mm),
					o = k.values[a - 1][2],
					ii = parseFloat(o);
					ret.maxMarches = ret.maxMarches + ii;
				}
			}
			break;
		}
	}
	var e = 1;
	var f = uW.unixtime();
	if (Seed.playerEffects.aurasExpire && Seed.playerEffects.aurasExpire > f) e = 1.15;
	if (Seed.playerEffects.auras2Expire && Seed.playerEffects.auras2Expire > f) e = 1.3;
	var e25 = e + 0.25;
	var e50 = e + 0.5;		
	if (uW.cm.PrestigeModel.isPrestige(cityId)) {
		var b = uW.cm.PrestigeModel.getPrestigeLevel(cityId);
		if (b > 0) {
			var r = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
			m = uW.JSON.parse(r),
			u = m.values[b - 1][1],
			k = parseFloat(u);
			e *= k;
			e25 *= k;
			e50 *= k;
		}
	}
	var maxsend = parseInt(ret.level * 10000 * e);
	var maxsend25 = parseInt(ret.level * 10000 * e25);
	var maxsend50 = parseInt(ret.level * 10000 * e50);
	if (ret.level == 11) {
		var maxsend = parseInt(150000 * e);
		var maxsend25 = parseInt(150000 * e25);
		var maxsend50 = parseInt(150000 * e50);
	}
	if (ret.level == 12) {
		var maxsend = parseInt(200000 * e);
		var maxsend25 = parseInt(200000 * e25);
		var maxsend50 = parseInt(200000 * e50);
	}
	var q = uW.cm.ThroneController.effectBonus(66);
	if (q > 150) q = 150;
	ret.maxMarchSize = Math.round(maxsend * (1 + q / 100));
	ret.maxMarchSize25 = Math.round(maxsend25 * (1 + q / 100));
	ret.maxMarchSize50 = Math.round(maxsend50 * (1 + q / 100));
	//Blessing FILL_THE_RANKS
	var blessing = uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().FILL_THE_RANKS, cityId, {marchsize: true});
	ret.maxMarchSize = Math.round(ret.maxMarchSize * blessing);
	ret.maxMarchSize25 = Math.round(ret.maxMarchSize25 * blessing);
	ret.maxMarchSize50 = Math.round(ret.maxMarchSize50 * blessing);
	var slots = 0;
	for (var k in Seed.queue_atkp[city]){
		var m = Seed.queue_atkp[city][k];
		if (typeof (m) == 'object') slots++;
	}
	ret.usedSlots = slots;
	ret.freeSlots = ret.maxMarches - slots;
	return ret;
}

function getWallInfo (cityId, objOut){
	objOut.wallSpaceUsed = 0;
	objOut.fieldSpaceUsed = 0;
	objOut.wallLevel = 0;
	objOut.wallSpace = 0;
	objOut.fieldSpace = 0;
	objOut.Crossbows = 0;
	objOut.CrossbowsTraining = 0;
	objOut.Trebuchet = 0;
	objOut.TrebuchetTraining = 0;
	objOut.Caltrops = 0;
	objOut.CaltropsTraining = 0;
	objOut.SpikedBarrier = 0;
	objOut.SpikedBarrierTraining = 0;
	objOut.Trap = 0;
	objOut.TrapTraining = 0;
	objOut.slotsBusy = 0;
	objOut.loggingLevel = parseInt(Seed.tech["tch2"]);
	objOut.geometryLevel = parseInt(Seed.tech["tch5"]);
	objOut.eagleEyesLevel = parseInt(Seed.tech["tch6"]);
	objOut.poisonedEdgeLevel = parseInt(Seed.tech["tch8"]);
	objOut.metalAlloysLevel = parseInt(Seed.tech["tch9"]);
	objOut.featherweightPowderLevel = parseInt(Seed.tech["tch10"]);
	objOut.alloyHorseshoesLevel = parseInt(Seed.tech["tch12"]);
	objOut.fletchingLevel = parseInt(Seed.tech["tch13"]);
	objOut.giantsStrengthLevel = parseInt(Seed.tech["tch16"]);
	objOut.blacksmithLevel = 0;
	objOut.stableLevel = 0;
	objOut.workshopLevel = 0;
	var b = Seed.buildings["city" + cityId];
	if (b.pos1==null)
		return;
	objOut.wallLevel = parseInt(b.pos1[1]);
	for (var j=1; j<33; j++){
		if (b['pos'+j]) {
			var bname = parseIntNan(b['pos'+j][0]);
			var blvl = parseIntNan(b['pos'+j][1]);
			if (bname==16)
				objOut.blacksmithLevel = blvl;
			if (bname==15)
				objOut.workshopLevel = blvl;
			if (bname==17)
				objOut.stableLevel = blvl;
		}
	}
	var isPrestige = Seed.cityData.city[cityId].isPrestigeCity;
   	if(isPrestige){
   		objOut.blacksmithLevel = 12;
   		objOut.workshopLevel = 12;
   		objOut.stableLevel = 12;
	}
	var spots = 0;
	for (var i=1; i<(objOut.wallLevel+1); i++)
		spots += (i * 500);
	objOut.wallSpace = spots;
	objOut.fieldSpace = spots;

	var fort = Seed.fortifications["city" + cityId];
	for (k in fort){
		var id = parseInt(k.substr(4));
		if (id == 53)
			objOut.Crossbows = parseInt(fort[k]);
		else if (id == 55)
			objOut.Trebuchet = parseInt(fort[k]);
		else if (id == 60)
			objOut.Trap = parseInt(fort[k]);
		else if (id == 61)
			objOut.Caltrops = parseInt(fort[k]);
		else if (id == 62)
			objOut.SpikedBarrier = parseInt(fort[k]);
		if (id<60)
			objOut.wallSpaceUsed += parseInt(uW.fortstats["unt"+ id][5]) * parseInt(fort[k]);
		else
			objOut.fieldSpaceUsed += parseInt(uW.fortstats["unt"+ id][5]) * parseInt(fort[k]);
	}
	var q = Seed.queue_fort["city"+cityId];
	if (q && q.length>0) {
		for (qi=0; qi<q.length; qi++) {
			objOut.slotsBusy++;
			if (q[qi][0]==53)
				objOut.CrossbowsTraining += parseInt(q[qi][1]);
			if (q[qi][0]==55)
				objOut.TrebuchetTraining += parseInt(q[qi][1]);
			if (q[qi][0]==60)
				objOut.TrapTraining += parseInt(q[qi][1]);
			if (q[qi][0]==61)
				objOut.CaltropsTraining += parseInt(q[qi][1]);
			if (q[qi][0]==62)
				objOut.SpikedBarrierTraining += parseInt(q[qi][1]);
		}
	}
	objOut.Def53Time = ((objOut.wallLevel > 5 && objOut.blacksmithLevel > 5 && objOut.fletchingLevel > 4)?true:false);
	objOut.Def55Time = ((objOut.wallLevel > 7 && objOut.blacksmithLevel > 7 && objOut.fletchingLevel > 6 && objOut.geometryLevel > 6)?true:false);
	objOut.Def60Time = ((objOut.wallLevel > 3 && objOut.blacksmithLevel > 3 && objOut.poisonedEdgeLevel > 1)?true:false);
	objOut.Def61Time = ((objOut.wallLevel > 0 && objOut.metalAlloysLevel > 0)?true:false);
	objOut.Def62Time = ((objOut.wallLevel > 1 && objOut.blacksmithLevel > 1 && objOut.loggingLevel > 1)?true:false);
}
Tabs.Overview = {
	tabOrder: TabOptions.toOverview,
	tabLabel: culang.tabLabelOverview,
	myDiv: null,
	craftitems : {},
	displayTimer : null,
	checkBox:null,
	defMode : {},
	checkBox1:null,
	Overview : function (){
	},

	switchGuardian: function(numCity, type) {
		var t = Tabs.Overview;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action = "summon";
		params.ctrl = "Guardian";
		params.cityId = Cities.cities[numCity].id;
		params.tvuid = getMyUserId();
		params.type = type;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					var g = Seed.guardian[numCity];
					var now = unixTime();
					g.summonGuardian = {
						summonFinishTime: parseInt(rslt.summonFinishTime),
						level: rslt.summonGuardian.cl0,
						type: rslt.summonGuardian.type,
						upgrading: false
					};
					setTimeout(function () {t.finalGuardian(numCity, rslt); }, (parseInt(rslt.summonFinishTime) - now)*1000);
					t.show();
				}
			},
		});
	},
	
	finalGuardian: function(numCity, rslt) {
		var t = Tabs.Overview;
		var g = Seed.guardian[numCity];
		g.timeLeft = 0;
		g.level = rslt.summonGuardian.cl0;
		g.type = rslt.summonGuardian.type;
		g.upgrading = false;
		if (g.summonGuardian) {
			delete g.summonGuardian;
		}
		t.show();
	},
	
	init : function (div){
		var t = Tabs.Overview;
		uW.switchGuardian = t.switchGuardian;
		for(var i=0; i < uW.recipelist[1].length; i++){
			var h = parseInt(uW.recipelist[1][i].output_item_id);
			t.craftitems[uW.recipelist[1][i].recipe_id] = h;
		}
		for(var i=0; i < uW.recipelist[3].length; i++){
			var h = parseInt(uW.recipelist[3][i].output_item_id);
			t.craftitems[uW.recipelist[3][i].recipe_id] = h;
		}
		t.myDiv = div;
		var str= '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'statsTabOptions\').style.display=(document.getElementById(\'statsTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadStats+'</a></div>\
        <DIV id="statsTabOptions" style="display:none;">\
        <TABLE class=pdxTab>\
            <TR><TD width="20"><INPUT id=togShowTroops  type=checkbox /></td><TD width="300">'+culang.optionsStatsTabShowTroops+'</td><TD width="20"><INPUT id=togShowDefense  type=checkbox /></td><TD width="238">'+culang.optionsStatsTabShowDef+'</td></tr>\
            <TR><TD><INPUT type=checkbox id=togShowRes /></td><TD>'+culang.optionsStatsTabShowRes+'</td><TD><INPUT type=checkbox id=ptEnableReduireUnit /></td><TD>'+culang.optionsStatsTabShortValues+'</td></tr>\
            <TR><TD><INPUT type=checkbox id=togShowProduction /></td><TD>'+culang.optionsStatsTabShowResProduction+'</td><TD><input type=checkbox id=togShowPop /></td><TD>'+culang.optionsStatsTabShowPop+'</td></tr>\
            <TR><TD><INPUT type=checkbox id=togincludeMarching /></td><TD>'+culang.optionsStatsTabShowMarches+'</td><TD>&nbsp;</td><TD>&nbsp;</td></tr>\
            <TR><TD><INPUT type=checkbox id=togEnableFormation /></td><TD>'+culang.optionsStatsTabTrainTroops+'</td><TD>&nbsp;</td><TD>&nbsp;</td></tr>\
            <TR><TD><INPUT type=checkbox id=ptEnableFoodWarn /></td><TD colspan=3>'+culang.optionsStatsTabFoodLeft+' <INPUT type=text id=optFoodHours value="'+ Options.foodWarnHours +'" size=3> '+culang.optionsStatsTabFoodLeft2+'</td></tr></table>\
        </div><div id="KsResumeDIV" style="max-height:' + (Options.HauteurBoite-100) +'px;overflow-y:auto"></div>\
        ';
		t.myDiv.innerHTML = str;
		t.KsResumeDIV = ById("KsResumeDIV");
	},
	getContent : function (){
	},

	hide : function (){
		var t = Tabs.Overview;
		clearTimeout (t.displayTimer);
	},
	show : function (){
		var t = Tabs.Overview;
		clearTimeout (t.displayTimer);
		t.setContent();
	},
	setContent : function (){
		var t = Tabs.Overview;
		var rownum = 0;
		var totalentre = 0;
		function UniteFormation(id) {
			var nbunit=0; // 
			for(i=0; i<Cities.numCities; i++) {
				var cityIdd = Cities.cities[i].id;
				var q = Seed.queue_unt['city'+cityIdd];
				var qs = q.toString();
				if (q!=null && q.length>0 ){
					for (var ii=0; ii<q.length; ii++){
						if (q[ii][0]==id) nbunit+=parseIntNan(q[ii][1]);

					}
				}
			}
			totalentre += parseIntNan(nbunit*UniteCout(id));
			return nbunit;
		}
		function UniteCout(id) {
			var Unitcout=parseIntNan(uW.unitupkeeps[id]);
			return Unitcout;
		}

		function _row (name, row, noTotal, typee){
			if (rownum++ % 2) {
				var style = '';
				var style2 = ' style = "background: #ffc"';
			} else {
				var style = ' style = "background: #e8e8e8"';
				var style2 = ' style = "background: #eea"';
			}
			var tot = 0;
			var m = [];
			m.push ('<TR style="background: #fff" align=right');
			m.push (style);
			m.push ('><TD');
			m.push (style);
			m.push ('><B>');
			m.push (name);
			m.push ('</td>');
			if (noTotal){
				m.push ('<TD');
				m.push (style);
				m.push ('>&nbsp;</td>');
			} else {
				for (i=0; i<row.length; i++)
					tot += row[i];
				m.push ('<TD'+style2+'>');
				if (tot<0) {
					m.push ("<SPAN class=boldRed>"+UniteKMG(tot)+"</span>");
				} else {
					if (typee>0 || !Options.EnableReduireUnit)
						m.push (addCommas(tot));
					else
						m.push (UniteKMG(tot));
				}
				m.push ('</td>');
			}
			for (i=0; i<row.length; i++){
				m.push ('<TD');
				m.push (style);
				m.push ('>');
				if (typee>0 || !Options.EnableReduireUnit)
					m.push (addCommas(row[i]));
				else
					m.push (UniteKMG(row[i]));
				m.push ('</td>');
			}
			if (Options.EnableFormation && typee>0) {
				m.push ('<td'+style+'>'+addCommas(UniteFormation(typee))+'</td>');
			}
			if (Options.EnableFormation && name==''+culang.overviewSTrain+'') {
				if (!Options.EnableReduireUnit)
					m.push('<td'+style+'>&nbsp;</td><td'+style+'>' + addCommas(totalentre) + "</td>");
				else
					m.push('<td'+style+'>&nbsp;</td><td'+style+'>' + UniteKMG(totalentre) + "</td>");
			}
			m.push ('</tr>');
			return m.join('');
		}

		try {
			if (Options.includeMarching)
				march = getMarchInfo ();

			dt = new Date ();
			dt.setTime (Seed.player.datejoinUnixTime * 1000);
			allianceId=(typeof(Seed.allianceDiplomacies)=='undefined')?"undefined":Seed.allianceDiplomacies.allianceId;

			str = '<DIV class=pdxStatOverview style="margin-top:4px;">\
			<table width="100%" border="0" cellspacing="0" cellpadding="0" class=pdxTab>\
			<tr>\
			<td class=pdxStatLight><sup><a href="http://kocmon.com/'+getServerId()+'/" target="_blank" title="'+culang.overviewSeverStatsNote+'">' + uW.domainName +'</a></sup></td>\
			<td class=pdxStatLight><sup><a href="http://kocmon.com/'+getServerId()+'/search-for-alliance" target="_blank" title="'+culang.overviewAllianceSearchNote+'">'+uW.g_js_strings.commonstr.alliance+'</a></sup></td>\
			<td class=pdxStatLight><sup><a href="http://kocmon.com/'+getServerId()+'/highest-might" target="_blank" title="'+culang.overviewMightLeaderboardNote+'">'+uW.g_js_strings.commonstr.might+'</a></sup></td>\
			<td><sup>'+uW.g_js_strings.commonstr.glory+'</sup></td>\
			<td><sup>'+culang.overviewPlaySince+'</sup></td>\
			<td><sup>'+culang.overviewThrone+'</sup></td>\
			</tr><tr>\
			<td class=pdxStatLight><span ><a href="http://kocmon.com/'+getServerId()+'/players/'+parseInt([Seed.tutorial.userId])+'" target="_blank" title="'+culang.overviewPlayerStatsNote+'"> ' + Seed.player['name'] + '</a> </span></td>\
			<td class=pdxStatLight><span ><a href="http://kocmon.com/'+getServerId()+'/alliances/'+allianceId+'" target="_blank" title="'+culang.overviewAllianceStatsNote+'"> ' + getMyAlliance()[1] +'</a></span></td>\
			<td><span>' + addCommas(Seed.player.might) +'</span></td>\
			<td><span >' + addCommas(Seed.player.glory) +' (' + addCommas(Seed.player.maxGlory) +')</span></td>\
			<td><span >'+ dt.toLocaleDateString() +'</span></td>\
			<TD><SPAN title="'+culang.overviewThroneMightNote+'">'+addCommas(uW.cm.ThroneController.calcMight())+'</span></td></tr>\
			</table></div><span id="debugtest"></span>';
			str += "<DIV id=overMainDiv style='font-size:10px;padding:5px'><TABLE class=pdxTabOverview cellpadding=0 cellspacing=0><TR  align=center><TD width=45 align=center></td><TD width=88 style='background: #ffc; font-size:150%' align=center><SPAN class=shadowCaps>"+culang.mainTotal+"</SPAN></td>";
			for(i=0; i<Cities.numCities; i++) {
				cityID = 'city'+ Cities.cities[i].id;
				Gate = parseInt(Seed.citystats[cityID].gate);
				if(Gate == 0) var couleurr="#77EE77";
				if(Gate != 0) var couleurr="#EE7777";

				str += "<TD width=80 style='background-color:"+couleurr+"'><SPAN class=shadowCaps>"+ Cities.cities[i].name.substring(0,10) +"</SPAN><BR><a href='javascript:void(0)' onclick='clickKoords(event)' class='coordinateLink'>("+Cities.cities[i].x +","+ Cities.cities[i].y+")</a><BR>"+ uW.provincenames['p'+ Cities.cities[i].provId] +"</td>";
			}

			if (Options.includeMarching)
				str += '<TD width=81><B>'+culang.mainMarches+'</b></td>';
			if (Options.EnableFormation)
				str += "<TD width=81><B>"+culang.overviewSTrain+"</b></td>";

			str += "<td></td></tr>";
			str += "<tr><td><DIV id=pbSwfPlayer></div></td><td></td>";

			for (var cityId in Cities.byID)
				str += '<TD align=center><INPUT type=submit id=ksDefBtn_'+ cityId +' value=""></td>';
			str += '</tr>';
			//Guardians
			str += '<tr><td style="text-align:right;"><img title="'+uW.g_js_strings.guardian.guardians+'" width=20 src="'+IMGWoodGuardian+'"></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				var ag = Seed.guardian[i];
				var gis = ag.cityGuardianLevels;
				str+='<td style="text-align:center;">';
				if (gis.wood) {
					if (ag.type == 'wood') var b = 'style="border:1px solid red;"';
						else var b = 'onclick="switchGuardian('+i+',\'wood\')" style="border:1px solid transparent;"';
					if (ag.summonGuardian) var b = 'style="border:1px solid silver;"';
					str += '<img '+b+' title= "'+uW.buildingcost.bdg50[0] + ' Level ' + gis.wood +'" width=20 src="'+IMGWoodGuardian+'">';
				}
				if (gis.ore) {
					if (ag.type == 'ore') var b = 'style="border:1px solid red;"';
						else var b = 'onclick="switchGuardian('+i+',\'ore\')" style="border:1px solid transparent;"';
					if (ag.summonGuardian) var b = 'style="border:1px solid silver;"';
					str += '<img '+b+' title= "'+uW.buildingcost.bdg51[0] + ' Level ' + gis.ore +'" width=20 src="'+IMGOreGuardian+'">';
				}
				if (gis.food) {
					if (ag.type == 'food') var b = 'style="border:1px solid red;"';
						else var b = 'onclick="switchGuardian('+i+',\'food\')" style="border:1px solid transparent;"';
					if (ag.summonGuardian) var b = 'style="border:1px solid silver;"';
					str += '<img '+b+' title= "'+uW.buildingcost.bdg52[0] + ' Level ' + gis.food +'" width=20 src="'+IMGFoodGuardian+'">';
				}
				if (gis.stone) {
					if (ag.type == 'stone') var b = 'style="border:1px solid red;"';
						else var b = 'onclick="switchGuardian('+i+',\'stone\')" style="border:1px solid transparent;"';
					if (ag.summonGuardian) var b = 'style="border:1px solid silver;"';
					str += '<img '+b+' title= "'+uW.buildingcost.bdg53[0] + ' Level ' + gis.stone +'" width=20 src="'+IMGStoneGuardian+'">';
				}
				str+='</td>';
			}
			str += '</tr>';
			
			// Ascension
			row = [];
			var adata = uW.cm.WorldSettings.getSettingAsObject("ASCENSION_REQS_DRUID");	
			for(i=0; i<Cities.numCities; i++) {
				var cityId = Cities.cities[i].id;
				if (Seed.cityData.city[cityId].isPrestigeCity) {
					var atype = Seed.cityData.city[cityId].prestigeInfo.prestigeType;
					if (atype == 1) {
						var adata = uW.cm.WorldSettings.getSettingAsObject("ASCENSION_REQS_DRUID");	
					} else if (atype == 2) {
						var adata = uW.cm.WorldSettings.getSettingAsObject("ASCENSION_REQS_FEY");	
					} else {
						var adata = uW.cm.WorldSettings.getSettingAsObject("ASCENSION_REQS_BRITON");	
					}
					var alevel = Seed.cityData.city[cityId].prestigeInfo.prestigeLevel;
					var avalue = Seed.cityData.city[cityId].cityValue;
					if (adata[parseInt(alevel)+1] != null) {
						var amin = adata[parseInt(alevel)+1].min;
						var amax = adata[parseInt(alevel)+1].max;
						if (avalue == 0) {
							var aproz = '';
						} else if (avalue < amin) {
							var aproz = ' (0%)';
						} else if (avalue >= amax) {
							var aproz = ' (<b style="color:green;">100%</b>)';
						} else {
							var aproz = ' (' + Math.round(1000*(avalue - amin)/(amax - amin))/10 + '%)';
						}
					} else {
						var aproz = '';
					}
					
					if (atype == 1) {
						row[i] = '<p style="text-align: center; margin:0;"><B>' + culang.mainCityDruid + '<br>Level '+alevel+'</b>'+aproz+'</p>'; //15.10.2012 Bommel
					} else if (atype == 2) {
						row[i] = '<p style="text-align: center; margin:0;"><B>' + culang.mainCityFey + '<br>Level '+alevel+'</b>'+aproz+'</p>'; //15.10.2012 Bommel
					} else {
						row[i] = '<p style="text-align: center; margin:0;"><B>' + culang.mainCityBriton + '<br>Level '+alevel+'</b>'+aproz+'</p>'; //15.10.2012 Bommel
					} 
				} else {
					var avalue = Seed.cityData.city[cityId].cityValue;
					var amin = adata[1].min;
					var amax = adata[1].max;
					if (avalue < amin) {
						var aproz = '0%';
					} else if (avalue >= amax) {
						var aproz = '<b style="color:green;">100%</b>';
					} else {
						var aproz = Math.round(1000*(avalue - amin)/(amax - amin))/10 + '%';
					}
					row[i] = '<p style="text-align: center; margin:0;">'+aproz+'</p>';					
				}
			}
			str += _row ('Asc.', row, true, 0);
	
			//Sammelplatz
			row = [];
			for(i=0; i<Cities.numCities; i++) {
				var RInfo = getRallypointInfo(Cities.cities[i].id);
				row[i] = '<SPAN><B>'+ RInfo.usedSlots +'/'+ RInfo.maxMarches +'</b><br>'+RInfo.maxMarchSize+'</span>';
			}
			str += _row ('<img src="'+IMGrallypoint18+'" alt="'+culang.mainSRallyPoint+'" title="'+culang.mainSRallyPoint+'">', row, true, 0);
			
			rows = [];
			rowsnm = [];
			rows[0] = [];
			// Ressources
			if (Options.showRes) {
				for(i=0; i<Cities.numCities; i++) {
					cityID = 'city'+ Cities.cities[i].id;
					rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
				}
				for (r=1; r<6; r++){
					rows[r] = [];
					for(i=0; i<Cities.numCities; i++) {
						cityID = 'city'+ Cities.cities[i].id;
						if (r==5)
							rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
						else
							rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);

					}

				}

				if (Options.includeMarching){
					for (var i=0; i<6; i++)
						rows[i][Cities.numCities] = parseIntNan(march.resources[i]);
				}
				str += _row ('<img height=18 src="'+IMGgold30+'">', rows[0], false, 0);
				str += _row ('<img height=18 src="'+IMGfood30+'">', rows[1], false, 0);
				str += _row ('<img height=18 src="'+IMGwood30+'">', rows[2], false, 0);
				str += _row ('<img height=18 src="'+IMGstone30+'">', rows[3], false, 0);
				str += _row ('<img height=18 src="'+IMGiron30+'">', rows[4], false, 0);
				str += _row ('<img height=18 src="'+IMGastone30+'">', rows[5], false, 0);

				//Storehouse
				rows = [];
				var STOREHOUSE = [0,100000,200000,300000,400000,500000,600000,700000,800000,900000,1000000,5000000,50000000];
				for(i=0; i<Cities.numCities; i++) {
					var cityID = 'city'+ Cities.cities[i].id;
					var sh = getCityBuilding(Cities.cities[i].id,9);
					if (sh.count == 0) {
						rows[i] = '0';
					} else {
						var MaxStorehouse = uW.cm.thronestats.boosts.Storehouse.Max;
						var TR = Math.min(uW.cm.ThroneController.effectBonus(89), MaxStorehouse);
						rows[i] = Math.round(STOREHOUSE[sh.maxLevel] * (1 + Seed.tech.tch14/10 + TR/100));
					}
				}
				str += _row ('<img title="'+uW.buildingcost.bdg9[0]+'" height=18 src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/storehouse_lvl10_26.png">', rows, true, 0);
				
				if (Options.showProduction) {

					str += '<TR><TD><BR></td></tr>';

					row = [];
					for(i=0; i<Cities.numCities; i++) {
						var rp = getResourceProduction (Cities.cities[i].id);
						row[i] = rp[1];
					}
					str += _row ('<img height=18 title="'+culang.overviewFoodProduce+'" src="'+IMGfood30+'">', row, false, 0);
					row = [];
					for(i=0; i<Cities.numCities; i++) {
						var rp = getResourceProduction (Cities.cities[i].id);
						row[i] = rp[2];
					}
					str += _row ('<img height=18 title="'+culang.overviewWoodProduce+'" src="'+IMGwood30+'">', row, false, 0);

					row = [];
					for(i=0; i<Cities.numCities; i++) {
						var rp = getResourceProduction (Cities.cities[i].id);
						row[i] = rp[3];
					}
					str += _row ('<img height=18 title="'+culang.overviewStoneProduce+'" src="'+IMGstone30+'">', row, false, 0);

					row = [];
					for(i=0; i<Cities.numCities; i++) {
						var rp = getResourceProduction (Cities.cities[i].id);
						row[i] = rp[4];
					}
					str += _row ('<img height=18 title="'+culang.overviewIronProduce+'" src="'+IMGiron30+'">', row, false, 0);

				}


			}


			var now = unixTime();
			str += '<TR><TD style="font-size:6px"><BR></font></td></tr>';
			str +='<tr style="background: #fff" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/131.jpg title="'+culang.mainBuildTime+'"></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				var totTime = 0;
				if (Seed.queue_con["city" + Cities.cities[i].id].length > 0) {
					var q=Seed.queue_con["city" + Cities.cities[i].id][0];
					var level = q[1];
					var type = q[0];
					var title = uW.buildingcost['bdg'+type][0] + ' Lvl. ' + level;  
					var totTime = 0;
					totTime = q[4] - now;
					if (totTime < 0)
						totTime = 0;
					if (totTime < 3600)
						affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
					else
						affuichage = timestr(totTime);
					str +='<td><span title="'+title+'">'+ affuichage + "</span></td>";
				} else {
					str +="<td>0s</td>";
				}
			}
			str +="</tr>";
			//
			str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1.jpg title="'+culang.mainResearch+'"></b></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
					str +="<td>";
				var totTime = 0;
				if (Seed.queue_tch["city" + Cities.cities[i].id].length > 0) {
					var q=Seed.queue_tch["city" + Cities.cities[i].id][0];
					var level = q[1];
					var type = q[0];
					var title = uW.techcost['tch'+type][0] + ' Lvl. ' + level;  
					var totTime = 0;
					totTime = q[3] - now;
					if (totTime < 0)
						totTime = 0;
					if (totTime < 3600)
						affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
					else
						affuichage = timestr(totTime);

					str += '<span title="'+title+'">'+ affuichage + '</span>';

				} else {
					str +="0s";
				}
				//Neue Forschungen
				var totTime = 0;
				if (Seed.queue_tch2["city" + Cities.cities[i].id].length > 0) {
					var q=Seed.queue_tch2["city" + Cities.cities[i].id][0];
					var level = q[1];
					var type = q[0];
					var title = uW.techcost2['tch'+type][0] + ' Lvl. ' + level;  
					var totTime = 0;
					totTime = q[3] - now;
					if (totTime < 0)
						totTime = 0;
					if (totTime < 3600)
						affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
					else
						affuichage = timestr(totTime);

					str += '<br><span title="'+title+'">' + affuichage+ '</span>';

				} 				
				str +="</td>"
			}
			str +="</tr>";
			// crafting
			str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/3.jpg title="'+culang.mainCrafting+'"></b></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				var totTime = 0;
				if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
					var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
					var h = t.craftitems[q.recipeId];
					var title = uW.itemlist["i"+h].name;
					var totTime = 0;
					totTime = q.craftingEtaUnixTime - now;
					if (totTime < 0)
						totTime = 0;
					if (getCityBuilding(Cities.cities[i].id,20).count>0 && totTime == 0)
						affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
					else
						affuichage = timestr(totTime);

					str +="<td><span title='"+title+"'>"+ affuichage + "</span></td>";

				} else {
					affuichage = timestr(totTime);
					if (getCityBuilding(Cities.cities[i].id,20).count>0)
						affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';

					str +="<td><span>"+affuichage+"</span></td>";
				}
			}
			str +="</tr>";
			// Reviving
			str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src="'+URL_HOSPITAL+'" title="'+culang.overviewHospitalNote+'"></b></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				str +="<td>";
				var totTime = 0;
				if (Seed.queue_revive["city" + Cities.cities[i].id].length > 0) {
					var q = Seed.queue_revive["city" + Cities.cities[i].id][0];
					var unit = q[0];
					var anz = q[1];
					var title = addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0];  
					totTime = q[3] - now;
					if (totTime < 0)
						totTime = 0;
					affuichage = timestr(totTime);
					str += '<span title="'+title+'">'+ affuichage + '</span>';
				} else {
					affuichage = timestr(totTime);
					str +="<span>"+affuichage+"</span>";				
				}

				//2.
				if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity && 
					uW.cm.BlessingSystemModel.isBlessingActive(uW.cm.BlessingSystemModel.getBlessing().ANCIENT_HEALING, Cities.cities[i].id)) {
					var totTime = 0;
					if (Seed.queue_revive2["city" + Cities.cities[i].id].length > 0) {
						var q = Seed.queue_revive2["city" + Cities.cities[i].id][0];
						var unit = q[0];
						var anz = q[1];
						var title = addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0];  
						totTime = q[3] - now;
						if (totTime < 0)
							totTime = 0;
						affuichage = timestr(totTime);
						str += '<br><span title="'+title+'">'+ affuichage + '</span>';
					} else {
						affuichage = timestr(totTime);
						str +="<br><span>"+affuichage+"</span>";
					}
				} 				
				str +="</td>";
			}
			str +="</tr>";
			
			//Opfer im Fey Altar
			str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src="'+IMGFeyAltar+'" title="'+uW.buildingcost.bdg25[0]+'"></b></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				str +="<td>";
				if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity) { 
					if (Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeType == 2) {
						// 1. Opfer
						var time = 0;
						if (Seed.queue_sacr["city" + Cities.cities[i].id].length > 0) {
							var q = Seed.queue_sacr["city" + Cities.cities[i].id][0];
							time = q.eta - now;
							var title = uW.unitnamedesctranslated['unt'+q.unitType][0] + ' +' + Math.round((q.multiplier[0] - 1) * 100)+'%';
							str += '<span title="'+title+'">'+timestr(time)+'</span>';
						} else {
							str += timestr(time);
						}
						//2. Opfer
						var time = 0;
						if (Seed.queue_sacr["city" + Cities.cities[i].id].length > 1) {
							var q = Seed.queue_sacr["city" + Cities.cities[i].id][1];
							time = q.eta - now;
							var title = uW.unitnamedesctranslated['unt'+q.unitType][0] + ' +' + Math.round((q.multiplier[0] - 1) * 100)+'%';
							str += '<br><span title="'+title+'">'+timestr(time)+'</span>';
						}
					} else {
						str +="---";
					}					
				} else {
					str +="---";
				}				
				str +="</td>";
			}
			str +="</tr>";
	
	
			// Population
			if (Options.showPop) {
				str += '<TR><TD style="font-size:6px"><BR></td></tr>';

				for (r=0; r<7; r++){
					rowsnm[r] = [];
				}
				for(i=0; i<Cities.numCities; i++) {
					cityID = 'city'+ Cities.cities[i].id;
					rowsnm[0][i] = parseIntNan(Seed.citystats[cityID]["pop"][1]);
					rowsnm[1][i] = parseIntNan(Seed.citystats[cityID]["pop"][0]);
					rowsnm[2][i] = parseIntNan(Seed.citystats[cityID]["pop"][3]);
					rowsnm[5][i] = parseIntNan(Seed.citystats[cityID]["pop"][2]);
					if (rowsnm[5][i] < 100)
						rowsnm[5][i] = '<SPAN class=boldRed>' + rowsnm[5][i] + '</SPAN>';
					rowsnm[3][i] = rowsnm[0][i] * rowsnm[5][i] / 100 - rowsnm[2][i];
					rowsnm[4][i] = rowsnm[1][i] - rowsnm[2][i];
					rowsnm[6][i] = parseIntNan(Seed.citystats[cityID]["gold"][1]);
					if (rowsnm[6][i] > 0)
						rowsnm[6][i] = '<SPAN class=boldRed>' + rowsnm[6][i] + '</SPAN>';
				}

				rownum = 0;
				str += _row (''+culang.overviewMaxPop+'',  rowsnm[0]);
				str += _row (''+culang.overviewSPop+'',  rowsnm[1]);
				str += _row (''+culang.mainWorker+'',  rowsnm[2]);
				str += _row (''+culang.mainMaxIdle+'', rowsnm[3]);
				str += _row (''+culang.mainIdle+'', rowsnm[4]);
				str += _row ('<img height=20 src="'+IMGhappiness+'" title="'+culang.mainLuck+'">',  rowsnm[5], true);
				str += _row ('<img height=20 src="'+IMGtaxes+'" title="'+culang.mainTax+'">', rowsnm[6], true);
			}

			str += '<TR><TD style="font-size:6px"><BR></td></tr>';
			row = [];
			var totalbouffe = 0;
			var MaxUpkeep = uW.cm.thronestats.boosts.Upkeep.Max;
			var TR = Math.min(uW.cm.ThroneController.effectBonus(79), MaxUpkeep) / 100;
		
			for(i=0; i<Cities.numCities; i++) {
				var rp = getResourceProduction (Cities.cities[i].id);
				var usage = parseIntNan(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
				usage = Math.floor(usage - (usage * TR));
				row[i] = rp[1] - usage;
			}
			str += _row ('<img src="'+IMGfoodplusminus20+'" alt="'+culang.overviewSProduce+'" title="'+culang.overviewSProduce+'">', row, false,  0);

			for(i=0; i<Cities.numCities; i++) {
				if (row[i] >= 0)
					row[i] = '----';
				else {
					var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
					if (timeLeft > 86313600)
						row[i] = '----';
					else {
						if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
							row[i] = '<SPAN class=whiteOnRed><blink>'+ timestrShort(timeLeft) +'</blink></span>';
						else
							row[i] = timestrShort(timeLeft);
					}
				}
			}
			str += _row ('<img src="'+IMGfoodleft20+'" alt="'+culang.overviewFoodLeft+'" title="'+culang.overviewFoodLeft+'">', row, true, 0);

			//Raids anzeigen
			//Werden Mehr als normal Resis geliefert?
			var bonus = 1;
			for(i=0; i<Cities.numCities; i++) {
				var marches = Seed.queue_atkp["city"+Cities.cities[i].id];
				for(ma in marches) {
					var m = marches[ma];
					if (m.marchType == 9 && m.botMarchStatus != 3) {
						if ((m.toTileLevel * 100000) < m.resource1) {
							bonus = m.resource1 / (m.toTileLevel * 100000);
						}
					}
				}
			}
			row = [];
			for(i=0; i<Cities.numCities; i++) {
				var raid = 0;
				var marches = Seed.queue_atkp["city"+Cities.cities[i].id];
				for(ma in marches) {
					var m = marches[ma];
					if (m.marchType == 9 && m.botMarchStatus != 3) {
					if (isNaN(m.returnUnixTime)) var retUT = m.returnEta; 
					else var retUT = m.returnUnixTime;
						var res = 3600/(retUT - m.marchUnixTime) * m.toTileLevel * 100000 *  bonus;
						raid += res;
					}
				}
				row[i] = parseInt(raid);
			}
			if (bonus > 1) {
				var bonus = Math.round((bonus - 1) * 100);
				str += _row ('Raid <span class="boldRed">+' +bonus +'%</span>', row, false, 0);
			} else {
				str += _row ('Raid', row, false, 0);
			}
			
			if (Options.showTroops) {

				str += '<TR><TD style="font-size:6px"><BR></td></tr>';
				for (r=1; r<18; r++){
					rows[r] = [];
					for(i=0; i<Cities.numCities; i++) {
						cityID = 'city'+ Cities.cities[i].id;
						rows[r][i] = parseIntNan(Seed.units[cityID]['unt'+r]);
					}
				}
				if (Options.includeMarching){
					for (var i=0; i<18; i++)
						// rows[i][Cities.numCities] = march.marchUnits[i];
						rows[i][Cities.numCities] = parseIntNan(march.marchUnits[i]);
				}
				rownum = 0;
				this.totalentre = 0;
				for (r=1; r<18; r++){
					str += _row ('<img height=18 title="'+uW.unitcost['unt'+r][0]+'" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+r+'_30.jpg>', rows[r],false, r);
				}
				str += '<TR><TD style="font-size:6px"><BR></font></td></tr>';
			}
			//Ausbildung #1
			str +='<tr style="background: #e8e8e8" align=right><td><img src="'+IMGtrain20+'" alt="'+culang.overviewSTrain+'" title="'+culang.overviewSTrain+'"></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				str += "<td>";
				var totTime = 0;
				var q = Seed.queue_unt['city'+Cities.cities[i].id];
				var max = 0;
				var title = '';
				if (q!=null && q.length>0) {
					for (var j = 0; j < q.length; j++) {
						if (!q[j][7]) {
							var unit = q[j][0];
							var anz = q[j][1];
							var qmax = parseInt(q[j][3]);
							var time = qmax - parseInt(q[j][2]);
							if (parseInt(q[j][2]) < now) var time = parseInt(q[j][3]) - now;
							if (qmax > now) 
								title += addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0] +' (' + timestr(time) +")\n";  
							if (qmax > max ) max = qmax;
						}
					}
					totTime = max - now;
					if (totTime < 0) totTime = 0;
				}
				if (totTime < 86400)
					str += '<SPAN title="'+title+'" class="boldRed"><B>'+ timestr(totTime) +'</b></span>';
				else
					str += '<SPAN title="'+title+'">'+timestr(totTime) + '</span>';
				//2.
				var totTime = 0;
				var q = Seed.queue_unt['city'+Cities.cities[i].id];
				var max = 0;
				var title = '';
				if (q!=null && q.length>0) {
					for (var j = 0; j < q.length; j++) {
						if (q[j][7]) {
							var unit = q[j][0];
							var anz = q[j][1];
							var qmax = parseInt(q[j][3]);
							var time = qmax - parseInt(q[j][2]);
							if (parseInt(q[j][2]) < now) var time = parseInt(q[j][3]) - now;
							if (qmax > now) 
								title += addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0] +' (' + timestr(time) +")\n";  
							if (qmax > max ) max = qmax;
						}
					}
					totTime = max - now;
					if (totTime < 0) totTime = 0;
				}
				if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity) {
					if (totTime < 86400)
						str += '<br><SPAN title="'+title+'" class="boldRed"><B>'+ timestr(totTime) +'</b></span>';
					else
						str += '<br><SPAN title="'+title+'">'+timestr(totTime) + '</span>';
				}
				
				str += "</td>";
			}
					
			// Defenses du remparts
			if (Options.showDefense) {
				str += '<TR><TD style="font-size:6px"><BR></td></tr>';
				owsnm = [];
				for (r=0; r<5; r++){
					rowsnm[r] = [];
				}
				for(i=0; i<Cities.numCities; i++) {
					var wall = {};
					getWallInfo (Cities.cities[i].id, wall);
					rowsnm[0][i] = parseIntNan(wall.Crossbows);
					rowsnm[1][i] = parseIntNan(wall.Trebuchet);
					rowsnm[2][i] = parseIntNan(wall.Caltrops);
					if (isNaN(parseInt(wall.SpikedBarrier))) // KoC bug if wall lvl 0
						rowsnm[3][i] = 0;
					else
						rowsnm[3][i] = parseIntNan(wall.SpikedBarrier);
					rowsnm[4][i] = parseIntNan(wall.Trap);
				}
				if (Options.defBau){
					var q = Seed.queue_unt;
					for(i=0; i<Cities.numCities; i++) {
						var q = Seed.queue_fort['city'+Cities.cities[i].id];
						if (q && q.length>0){
							for (qi=0; qi<q.length; qi++) {
								if (q[qi][0]==53)
									rowsnm[0][i] += parseIntNan(q[qi][1]);
								if (q[qi][0]==55)
									rowsnm[1][i] += parseIntNan(q[qi][1]);
								if (q[qi][0]==60)
									rowsnm[4][i] += parseIntNan(q[qi][1]);
								if (q[qi][0]==61)
									rowsnm[2][i] += parseIntNan(q[qi][1]);
								if (q[qi][0]==62)
									rowsnm[3][i] += parseIntNan(q[qi][1]);
							}
						}
					}
				}

				rownum = 0;
				str += _row ('<img height=18 title="'+uW.fortcost.frt53[0]+'" src="'+IMGmiddleCrossbows+'">',  rowsnm[0]);
				str += _row ('<img height=18 title="'+uW.fortcost.frt55[0]+'" src="'+IMGmiddleTrebuchet+'">',  rowsnm[1]);
				str += _row ('<img height=18 title="'+uW.fortcost.frt60[0]+'" src="'+IMGmiddleTrap+'">',  rowsnm[4]);
				str += _row ('<img height=18 title="'+uW.fortcost.frt61[0]+'" src="'+IMGmiddleCaltr+'">', rowsnm[2]);
				str += _row ('<img height=18 title="'+uW.fortcost.frt62[0]+'" src="'+IMGmiddleSpiked+'">',  rowsnm[3]);
			}

			
			str +='<tr style="background: #e8e8e8" align=right><td><img src="'+IMGwalltrain20+'" alt="'+culang.mainSDefense+'" title="'+culang.mainSDefense+'"></td><td>&nbsp;</td>';
			for(i=0; i<Cities.numCities; i++) {
				str += "<td>";
				var wall = {};
				getWallInfo (Cities.cities[i].id, wall);
				var totTime = 0;
				var q = Seed.queue_fort['city'+Cities.cities[i].id];
				var max = 0;
				var title = '';
				if (q!=null && q.length>0) {
					for (var j = 0; j < q.length; j++) {
						var unit = q[j][0];
						var anz = q[j][1];
						var qmax = parseInt(q[j][3]);
						if (qmax > now)
							title += addCommas(anz) + ' ' + uW.fortcost['frt'+unit][0] + "\n";  
						if (qmax > max ) max = qmax;
					}
					totTime = max - now;
					if (totTime < 0) totTime = 0;
				}
				if (totTime<1 && (wall.wallSpaceUsed < wall.wallSpace-4 || wall.fieldSpaceUsed < wall.fieldSpace-4))
					str += '<SPAN title="'+title+'" class=boldRed><B>'+ timestr(totTime) +'</b></span>';
				else
					str += '<SPAN title="'+title+'">'+ timestr(totTime) +'</span>';
					
				str += "</td>";
			}

			str += '<TR><TD style="font-size:6px"><BR></td></tr>';


			// Terres sauvages
			row = [];
			for(i=0; i<Cities.numCities; i++) {
				var totWilds = 0;
				dat = Seed.wilderness['city'+ Cities.cities[i].id];
				if (dat!=null && matTypeof(dat)=='object')
					for (k in dat)
						++totWilds;
				var nivcastle = parseInt(Seed.buildings['city'+ Cities.cities[i].id].pos0[1]);
				var castle = nivcastle;
				if (nivcastle==11) castle=12;
				if (nivcastle==12) castle=14;
				if (totWilds < castle)
				{
					row[i] = '<SPAN class=boldRed><B>'+ totWilds +'/'+ castle +'</b></span>';
				}else{

					row[i] = totWilds +'/'+ castle;
				}
			}
			str += _row ('<img src="'+IMGwild20+'" alt="'+culang.mainSWild+'" title="'+culang.mainSWild+'">', row, true, 0);
			row = [];
			var did = {};
			for(i=0; i<Cities.numCities; i++) {
				totKnights = 0;
				dat = Seed.knights['city'+ Cities.cities[i].id];
				for (k in dat)
					++totKnights;

				var Knidispo = 0;
				var niveauPointRall=parseInt(getCityBuilding (Cities.cities[i].id, 12).maxLevel);
				var add = 0;
				if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity) add = 3;
				if (niveauPointRall==12) niveauPointRall=11;  // fix : Send eleven armies at a time for level 12
				niveauPointRall = niveauPointRall + add;
				for (var iKR=0; iKR<knightRoles.length; iKR++){
					var leader = Seed.leaders['city'+Cities.cities[i].id][knightRoles[iKR][1]+'KnightId'];
					if (leader == 0) {

					}else{
						did['knt'+leader] = true;
					}
				}
				for (k in Seed.knights['city'+Cities.cities[i].id]){
					if (!did[k])
						Knidispo++;
				}
				if (Knidispo<niveauPointRall) {
					row[i] = '<b>' + totKnights + '</b> - <span title="'+culang.overviewKnightsCheck+'"><SPAN class=boldRed><B>'+Knidispo+'/' + niveauPointRall +'</span></span>';
				}else {
					row[i] = '<b>' + totKnights + '</b> - <span title="'+culang.overviewKnightsCheck+'">'+Knidispo+'/' + niveauPointRall +'</span>';
				}

			}
			str += _row ('<img src="'+IMGknights20+'" alt="'+culang.mainKnights+'" title="'+culang.mainKnights+'">', row, true, 0);
			str += "</table>";
			str += "<br><input id='ptButDebug' type='submit' name='SEED' value='DEBUG'>";
			//str += "<br><pre>"+inspect(uW.cm.thronestats.boosts,3) + "</pre>";
			t.KsResumeDIV.innerHTML = str +'</div>';

			document.getElementById('ptButDebug').addEventListener('click', function (){debugWin.doit()}, false);	
			
			
			function addListener (but, i){
				but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);
			}
			for (var cityId in Cities.byID){
				var but = document.getElementById ('ksDefBtn_'+ cityId);
				addListener (but, cityId);
				t.defMode[cityId] =  parseInt(Seed.citystats["city" + cityId].gate);
				t.displayDefMode (cityId);
			}

			Tabs.Options.togOpt ('ptEnableReduireUnit', 'EnableReduireUnit');
			Tabs.Options.togOpt ('togEnableFormation', 'EnableFormation');
			Tabs.Options.togOpt ('togShowDefense', 'showDefense');
			Tabs.Options.togOpt ('togShowProduction', 'showProduction');
			Tabs.Options.togOpt ('togincludeMarching', 'includeMarching');
			Tabs.Options.togOpt ('togShowTroops', 'showTroops');
			Tabs.Options.togOpt ('togShowPop', 'showPop');
			Tabs.Options.togOpt ('togShowRes', 'showRes');

			ById('optFoodHours').addEventListener ('change', function () {
				var x = ById('optFoodHours').value;
				if (isNaN(x) || x<0.01 || x>99999){
					ById('optFoodHours').value = Options.foodWarnHours;
					return;
				}
				Options.foodWarnHours = x;
				saveOptions();
			}, false);

		} catch (ex){
			t.KsResumeDIV.innerHTML = '<PRE>'+ ex.name +': '+ ex.message + " @"+ ex.lineNumber +'</pre>';
			GM_log(dump(ex,"ex",1));
		}
		t.displayTimer = setTimeout (t.setContent, 5000);
	},
	butToggleDefMode : function (cityId){
		var t = Tabs.Overview;
		var mode = 1;
		if (Seed.citystats["city" + cityId].gate != 0)
			mode = 0;
		t.ajaxSetDefMode (cityId, mode, function (newMode){
			t.defMode[cityId] = newMode;
			t.displayDefMode (cityId);
		});
	},

	displayDefMode : function (cityId){
		var t = Tabs.Overview;
		var but = ById('ksDefBtn_'+ cityId);
		if (t.defMode[cityId]){
			but.className = 'defButtonOn';
			but.value = ''+culang.mainHDef+' = '+culang.buttonON;
		} else {
			but.className = 'defButtonOff';
			but.value = ''+culang.mainHDef+' = '+culang.buttonOFF;
		}
	},
	ajaxSetDefMode : function (cityId, state, notify){
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid = cityId;
		params.state = state;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/gate.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					Seed.citystats["city" + cityId].gate = state;
					notify (state);
				}
			},
			onFailure: function () {
			}
		})
	},
};
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Reports.js">
//	
//	   KOC POWER - TABS REPORTS										        
//	


Tabs.Rpt = { //TODO rename to Reports
	tabOrder:		TabOptions.toReports,
	tabLabel:		culang.mainReports,
	cont:			null,
	state:			null,
	minPages:		parseInt(Options.arPageFrom),
	maxPages:		parseInt(Options.arPageTo),
	data:			[],
	dataDF:	[],dataAT:	[],
	report:			[],
	reportDF:		[],
	reportAT:		[],
	totalPages:	parseInt(Options.arPageTo),
	what:			'',
	whatNot:		'',
	content:		'',
	timer:null,

	show : function () {
		var t = Tabs.Rpt;
		if (Options.RptAuto) t.handleRptSearch();
	},
	hide : function (){
	},

	init : function (div) {
		var t = Tabs.Rpt;
		t.cont = div;
		uW.getmsg = t.getMailBody;
		uW.DelMail = t.DeleteMail;
		uW.getReport = t.getReportBody;
		uW.getReportAC = t.getReportBodyAC;
		uW.DelReport = t.DeleteReport;
		if (!Options.reportScanner.pause) Options.reportScanner.pause = 2;	
		var tc = '<DIV class=pdxStat>'+culang.reportsHead+' - <input type=button value="?" id=boaiderapport class=buttonHelp></DIV><DIV class=pdxEntry><TABLE><TR align=center valign=center>';
		tc += '<TD class=xtab style="line-height:30px;" align=right>'+culang.mainType+':&nbsp;<SELECT id="idRptType">';
		tc += '<OPTION value="alliance" ' + (Options.rptType=='alliance'?'SELECTED':'') + '>'+culang.reportAllianceReports+'</OPTION>';
		tc += '<OPTION value="player" ' + (Options.rptType=='player'?'SELECTED':'') + '>'+culang.reportPlayerReports+'</OPTION>';
		tc += '<OPTION value="inbox" ' + (Options.rptType=='inbox'?'SELECTED':'') + '>'+culang.reportInbox+'</OPTION>';
		tc += '<OPTION value="outbox" ' + (Options.rptType=='outbox'?'SELECTED':'') + '>'+culang.reportOutbox+'</OPTION></SELECT>';
		tc += '<BR /><INPUT id=idRptSearch type=submit value="'+culang.mainOK+'" />&nbsp;'+culang.reportAutoSearch+': <input type=checkbox id="idRptAuto" ' +(Options.RptAuto?'CHECKED':'')+'> '+culang.mainPage+':&nbsp;<INPUT id="idRptPageFrom" size=1 value="' + Options.arPageFrom + '">&#8211;<INPUT id="idRptPageTo" size=1 value="' + Options.arPageTo + '"></TD>';
		tc += '<TD class=xtab style="line-height:30px;" align=right>'+culang.mainAttacker+': &nbsp;<SELECT id="idRptAttacker">'; // Options.arPageFrom - Options.arPageTo
		tc += '<OPTION value="Them" ' + (Options.arAttacker=='Them'?'SELECTED':'') + '>'+culang.reportThemAttacker+'</OPTION>';
		tc += '<OPTION value="Us" ' + (Options.arAttacker=='Us'?'SELECTED':'') + '>'+culang.reportUsAttacker+'</OPTION>';
		tc += '<OPTION value="Both" ' + (Options.arAttacker=='Both'?'SELECTED':'') + '>'+culang.reportBothAttacker+'</OPTION></SELECT>';
		tc += '<BR />'+culang.mainTarget+':&nbsp;<SELECT id="idRptTarget">';
		tc += '<OPTION value="Them" ' + (Options.arTarget=='Them'?'SELECTED':'') + '>'+culang.reportThemTarget+'</OPTION>';
		tc += '<OPTION value="Us" ' + (Options.arTarget=='Us'?'SELECTED':'') + '>'+culang.reportUsTarget+'</OPTION>';
		tc += '<OPTION value="Both" ' + (Options.arTarget=='Both'?'SELECTED':'') + '>'+culang.reportBothTarget+'</OPTION></SELECT></TD>';
		tc += '<TD class=xtab style="line-height:30px;" align=right>'+culang.reportContain+':&nbsp;<INPUT id=idRptWhat type=text size=11 maxlength=50 value=""><BR />';
		tc += ''+culang.reportDifferent+':&nbsp;<INPUT id=idRptWhatNot type=text size=11 maxlength=50 value=""></TD>';
		tc += '<TD class=xtab style="line-height:30px;" align=left><INPUT id=idRptAttack type=checkbox '+(Options.arAttack?'CHECKED':'')+' />&nbsp;'+culang.mainAttack+'<BR />';
		tc += '<INPUT id=idRptScout type=checkbox '+(Options.arScout?'CHECKED':'')+' />&nbsp;'+culang.mainScout+'</TD>';
		tc += '<TD class=xtab style="line-height:30px;" align=left><INPUT id=idRptReinforce type=checkbox '+(Options.arReinforce?'CHECKED':'')+' />&nbsp;'+culang.mainReinforce+'<BR />';
		tc += '<INPUT id=idRptTransport type=checkbox '+(Options.arTransport?'CHECKED':'')+' />&nbsp;'+culang.mainTransport+'</TD>';
		tc += '<TD style="border-right:1px solid black;line-height:30px;" class=xtab align=left><select id=idRptFiltre1><option value="">--</option><option value="0">'+culang.mainWild+'</option><option value=54>'+culang.dfShort+'</option></select><br>'+culang.reportSynthesis+' <input type=checkbox id=KsSyntheseAttack></TD>';
		tc += '<TD class=xtab align=center style="line-height:30px;"><input id=reportScannerStart type=submit value="';
		if (Options.reportScanner.start) {
			tc += culang.reportScannerStartOn; //23.10.2012 Bommel
			Options.reportScanner.start = true;
		} else {
			tc += culang.reportScannerStartOff; //23.10.2012 Bommel
			Options.reportScanner.start = false;
		}
		tc += '"><br><INPUT id=reportScannerPause size="1" maxlength="3" type=text style="text-align:center;" value="'+Options.reportScanner.pause+'"> Min.</td>';
		tc += '</TR></TABLE></DIV>';
		tc += '<DIV class=pdxStat><TABLE width=100% cellspacing=0><TR><TD class=xtab align=left width=125><DIV id=idRptSearched></DIV></TD></TD>';
		tc += '<TD class=xtab><TD class=xtab align=center><SPAN style="white-space:normal" id=idRptStatus>&nbsp;</span></TD></TD>';
		tc += '<TD class=xtab><TD class=xtab align=right width=125><DIV id=idRptFound></DIV></TD></TR></TABLE></DIV>';
		tc += '<DIV id="idBoRptResultsDiv" style="max-height:' + (Options.HauteurBoite-140) +'px; overflow:auto; white-space:nowrap;"></DIV>';
		t.cont.innerHTML = tc;
		//ReportScanner
		ById('reportScannerStart').addEventListener('click', function(){t.RSStart();} , false);
		ById('reportScannerPause').addEventListener('change', function(){
			var value = parseIntNan(ById('reportScannerPause').value);
			if (value < 2) value = 2;
			Options.reportScanner.pause = value;
			saveOptions();
			ById('reportScannerPause').value = value;
			if (t.timer != null) {
				clearTimeout (t.timer);
				t.timer = setTimeout(t.RSTimer, Options.reportScanner.pause * 60000);				
			}
		} , false);
		
		ById('boaiderapport').addEventListener('click', function(){
			window.open(homePage+" ");
		} , false);

		ById('idRptType').addEventListener ('change', t.handleRptType, false);
		ById('idRptPageFrom').addEventListener ('change', t.handleRptPages, false);
		ById('idRptPageTo').addEventListener ('change', t.handleRptPages, false);
		ById('idRptAttacker').addEventListener ('change', t.handleRptAttacker, false);
		ById('idRptTarget').addEventListener ('change', t.handleRptTarget, false);
		ById('idRptWhat').addEventListener ('keyup', t.handleRptWhat, false);
		ById('idRptWhatNot').addEventListener ('keyup', t.handleRptWhatNot, false);
		ById('idRptSearch').addEventListener ('click', t.handleRptSearch, false);
		ById('idRptFiltre1').addEventListener ('change', t.handleRptWhat, false);

		t.togOpt ('idRptAttack', 'arAttack');
		t.togOpt ('idRptScout', 'arScout');
		t.togOpt ('idRptReinforce', 'arReinforce');
		t.togOpt ('idRptTransport', 'arTransport');
		t.togOpt ('idRptAuto','RptAuto');

	},
	RSStart: function() {
		var t = Tabs.Rpt;
		if (Options.reportScanner.start) {
			ById("reportScannerStart").value = culang.reportScannerStartOff; //23.10.2012 Bommel
			Options.reportScanner.start = false;
			ById("idRptType").disabled = false;
			clearTimeout (t.timer);
		} else {
			ById("reportScannerStart").value = culang.reportScannerStartOn; //23.10.2012 Bommel
			Options.reportScanner.start = true;
			ById("idRptType").value = "alliance";
			ById("idRptType").disabled = true;
			t.handleRptType();
			t.RSTimer();
		}
		saveOptions();
	},
	RSTimer : function() {
		var t = Tabs.Rpt;
		clearTimeout(t.timer);
    t.timer = setTimeout(t.RSTimer, Options.reportScanner.pause * 60000);
		t.handleRptSearch();
  },
	AutoStart: function() {
		var t = Tabs.Rpt;
		if (Options.reportScanner.start) {
			t.timer = setTimeout(t.RSTimer, 15000);
			ById("idRptType").value = "alliance";
			ById("idRptType").disabled = true;
			t.handleRptType();
		}
	},
	DeleteMail: function(rptid, type) {
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.requestType="ACTION_ON_MESSAGES";
		params.selectedAction="delete";
		params.boxType=ById('idRptType').value;
		params.selectedMessageIds=rptid;

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					t.handleRptSearch();
				}
				if (notify) //TODO Fehler: notify is not defined
					notify (rslt.errorMsg);
			},
			onFailure: function () {
				if (notify)
					notify ('AJAX ERROR');
			},
		});
	},

	DeleteReport: function(rptid, isUnread) {
		var t = Tabs.Rpt;

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.s0rids = rptid;
		params.s1rids = '';
		params.cityrids = '';

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/deleteCheckedReports.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {

					if (isUnread){
						uW.seed.newReportCount = parseInt(uW.seed.newReportCount) - 1;
						uW.messages_notify_bug()
					}
					//t.handleRptSearch();
					//t.DisplayRpt();
				}

			},
			onFailure: function () {
				t.handleRptSearch();
			},
		});
	},
	togOpt: function (checkboxId, optionName){
		var t = Tabs.Rpt;
		var checkbox = ById(checkboxId);
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (t.data.length > 0)
				if (Options.rptType == 'alliance' || Options.rptType == 'player')
					t.DisplayRpt();
				else
					t.DisplayMail();
		}
	},

	handleRptType: function(){
		var t = Tabs.Rpt;
		Options.rptType = ById("idRptType").value;
		saveOptions();
		ById("idRptSearched").innerHTML = '';
		ById("idRptStatus").innerHTML = '&nbsp;';
		ById("idRptFound").innerHTML = '';
		ById("idBoRptResultsDiv").innerHTML = '';
	},

	handleRptPages: function(){
		var t = Tabs.Rpt;
		t.minPages=parseInt(ById("idRptPageFrom").value);
		t.maxPages=parseInt(ById("idRptPageTo").value);
		if (t.maxPages < t.minPages) {
			t.maxPages = t.minPages;
			ById("idRptPageTo").value = t.maxPages;
		}
		Options.arPageFrom = t.minPages;
		Options.arPageTo = t.maxPages;
		saveOptions();
		t.totalPages=t.maxPages;
	},

	handleRptAttacker: function(){
		var t = Tabs.Rpt;
		Options.arAttacker = ById("idRptAttacker").value;
		saveOptions();
		if ((Options.rptType == 'alliance' || Options.rptType == 'player') && t.data.length > 0)
			t.DisplayRpt();
	},

	handleRptTarget: function(){
		var t = Tabs.Rpt;
		Options.arTarget = ById("idRptTarget").value;
		saveOptions();
		if ((Options.rptType == 'alliance' || Options.rptType == 'player') && t.data.length > 0)
			t.DisplayRpt();
	},

	handleRptWhat: function(){
		var t = Tabs.Rpt;
		t.what = ById("idRptWhat").value;
		if (t.data.length > 0)
			if (Options.rptType == 'alliance' || Options.rptType == 'player')
				t.DisplayRpt();
			else
				t.DisplayMail();
	},

	handleRptWhatNot: function(){
		var t = Tabs.Rpt;
		t.whatNot = ById("idRptWhatNot").value;
		if (t.data.length > 0)
			if (Options.rptType == 'alliance' || Options.rptType == 'player')
				t.DisplayRpt();
			else
				t.DisplayMail();
	},

	handleRptSearch: function(){
		var t = Tabs.Rpt;
		if (t.searchRunning){
			t.searchRunning = false;
			t.stopSearch (culang.mainCancel);
			return;
		}
		t.handleRptPages();
		document.getElementById ('idRptSearch').value = ''+culang.mainStop+'';
		ById('idRptStatus').innerHTML = culang.reportSearchedPages+' ' + t.minPages + ' / ' + t.maxPages;
		t.searchRunning = true;
		t.data=[];
		t.report = [];
		t.dataDF=[];
		t.dataAT=[];
		t.reportAT=[];
		t.reportDF = [];
		if (Options.rptType == 'alliance' || Options.rptType == 'player')
			t.getRpt(t.minPages);
		else
			t.getMail(t.minPages);
	},

	stopSearch: function (msg){
		var t = Tabs.Rpt;
		if (t.searchRunning || msg == culang.mainCancel)
			document.getElementById ('idRptStatus').innerHTML = '<FONT color=#ffaaaa>' + msg + '</FONT>';
		document.getElementById ('idRptSearch').value = ''+culang.mainOK+'';
		t.searchRunning = false;
		if (Options.rptType == 'alliance' || Options.rptType == 'player')
			t.DisplayRpt();
		else
			t.DisplayMail();
	},

	getMail: function (pageNum){
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pf=0;
		params.requestType="GET_MESSAGE_HEADERS_FOR_USER_INBOX";
		params.boxType = ById('idRptType').value;
		params.pageNo = pageNum;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				t.getMailCallback(rslt, pageNum);
			},
			onFailure: function () {
			},
		}, false);
	},

	getMailCallback: function(rslt, page) {
		var t = Tabs.Rpt;
		if (rslt) {
			if (!rslt.ok) {
				ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
				return;
			}
			t.totalPages=parseInt(rslt.noOfPages);
			if (t.totalPages < t.maxPages)
				t.maxPages = t.totalPages;
			if (rslt.message && page) {
				var ml = rslt.message;
				if (rslt.messageCount > 0) {
					var rptkeys = uW.Object.keys(ml);
					for (var i = 0; i < rptkeys.length; i++) {
						var rpt = ml[rptkeys[i]];
						rpt.page = page;
						t.data.push(rpt);
					}
				}
			}
			if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
				ById("idRptStatus").innerHTML = culang.reportSearchedPages+' ' + (parseInt(page)+1) + ' / ' + t.maxPages;
				t.getMail(parseInt(page)+1);
				if (t.data.length > 0)
					t.DisplayMail();
			} else if (page)
				t.stopSearch (''+culang.mainHDone+'');
		}
	},

	getRpt: function (pageNum){
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pageNo = pageNum;
		if (Options.rptType == 'alliance')
			params.group = "a";
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/listReports.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt){
				t.getRptCallback (rslt, pageNum);
			},
			onFailure: function (rslt){
				t.getRptCallback (rslt, pageNum);
			},
		}, false);
	},
	getRptCallback: function(rslt, page){
		var t = Tabs.Rpt;
		if (rslt) {
			if (!rslt.ok) {
				ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
				return;
			}
			t.totalPages=parseInt(rslt.totalPages);
			if (t.totalPages < t.maxPages)
				t.maxPages = t.totalPages;
			if (rslt.arReports && page) {
				var ar = rslt.arReports;
				//if (ar.length == 0)
				//t.stopSearch('Page vide trouve depuis la page ' + page + ' - Kabam glitch');
				var rptkeys = uW.Object.keys(ar);
				for (var i = 0; i < rptkeys.length; i++) {
					var rpt = ar[rptkeys[i]];
					var reportId = parseInt(rpt.reportId);
					t.report[reportId] = [];
					t.report[reportId].side1Name = rslt.arPlayerNames['p'+rpt.side1PlayerId];
					t.report[reportId].side1AllianceId = parseInt(rpt.side1AllianceId);
					if (rpt.side1AllianceId > 0)
						t.report[reportId].side1AllianceName = rslt.arAllianceNames['a'+rpt.side1AllianceId];
					else
						t.report[reportId].side1AllianceName = '-';
					if (rpt.side1CityId > 0)
						t.report[reportId].side1CityName = rslt.arCityNames['c'+rpt.side1CityId];
					else
						t.report[reportId].side1CityName = '-';
					t.report[reportId].side1XCoord = rpt.side1XCoord;
					t.report[reportId].side1YCoord = rpt.side1YCoord;
					if (parseInt(rpt.side0PlayerId) == 0) { // Kabam
						t.report[reportId].side0Name = ''+culang.reportEnemy+'';
						t.report[reportId].side0AllianceName = '';
						t.report[reportId].side0CityName = '';
					} else {
						t.report[reportId].side0Name = rslt.arPlayerNames['p'+rpt.side0PlayerId];
						if (rpt.side0AllianceId > 0)
							t.report[reportId].side0AllianceName = rslt.arAllianceNames['a'+rpt.side0AllianceId];
						else
							t.report[reportId].side0AllianceName = '-';
						if (rpt.side0CityId > 0)
							t.report[reportId].side0CityName = rslt.arCityNames['c'+rpt.side0CityId];
						else
							t.report[reportId].side0CityName = '-';
					}
					t.report[reportId].side0AllianceId = parseInt(rpt.side0AllianceId);
					t.report[reportId].side0XCoord = rpt.side0XCoord;
					t.report[reportId].side0YCoord = rpt.side0YCoord;
					if (parseInt(rpt.side0TileType) == 10)
						t.report[reportId].side0TileTypeText=culang.kocGrassland;
					else if (parseInt(rpt.side0TileType) == 11)
						t.report[reportId].side0TileTypeText=culang.kocLake;
					else if (parseInt(rpt.side0TileType) == 20)
						t.report[reportId].side0TileTypeText=culang.kocForests;
					else if (parseInt(rpt.side0TileType) == 30)
						t.report[reportId].side0TileTypeText=culang.kocHill;
					else if (parseInt(rpt.side0TileType) == 40)
						t.report[reportId].side0TileTypeText=culang.kocMount;
					else if (parseInt(rpt.side0TileType) == 50)
						t.report[reportId].side0TileTypeText=culang.kocPlain;
					else if (parseInt(rpt.side0TileType) == 51 && parseInt(rpt.side0CityId) == 0)
						t.report[reportId].side0TileTypeText=culang.mainCity;
					else if (parseInt(rpt.side0TileType) == 54)
						t.report[reportId].side0TileTypeText=culang.shortDarkForest;
					else if (parseInt(rpt.side0CityId) == 0)
						t.report[reportId].side0TileTypeText=culang.kocShortBarbarian;
					else
						t.report[reportId].side0TileTypeText=culang.mainCity;

					t.report[reportId].side0TileTypeLevel = t.report[reportId].side0TileTypeText + ' ' + rpt.side0TileLevel;
					t.report[reportId].side0TileType = rpt.side0TileType;
					t.report[reportId].side0TileLevel = rpt.side0TileLevel;
					t.report[reportId].page = page;
					t.report[reportId].reportUnixTime = rpt.reportUnixTime;
					if (rpt.side0AllianceId == parseInt(getMyAlliance()[0]))
						t.report[reportId].sideId = 0;
					else if (rpt.side1AllianceId == parseInt(getMyAlliance()[0])) {
						t.report[reportId].sideId = 1;
					} else {
						if (rpt.side0PlayerId == getMyUserId())
							t.report[reportId].sideId = 0;
						else if (rpt.side1PlayerId == getMyUserId())
							t.report[reportId].sideId = 1;
						else
							t.report[reportId].sideId = -1;
					}
					if (!ById("KsSyntheseAttack").checked && parseInt(rpt.side0TileType) == 54 && Options.rptType=='player') {
						t.FindItemRpt(reportId, t.report[reportId].sideId, t.report[reportId].side0TileLevel);
					}
					if (ById("KsSyntheseAttack").checked && (rpt.marchType == 4 || rpt.marchType == 3))
					{
						t.KsSyntheseAttack(reportId, t.report[reportId].sideId, 0);
					}
					t.report[reportId].marchType = rpt.marchType;
					if (rpt.marchType == 0)
						t.report[reportId].marchName = culang.mainDesertion;
					else if (rpt.marchType == 1)
						t.report[reportId].marchName = culang.mainTransport;
					else if (rpt.marchType == 2)
						t.report[reportId].marchName = culang.mainReinforced;
					else if (rpt.marchType == 3 || rpt.marchType == 11) {
						if (t.report[reportId].sideId == 0)
							t.report[reportId].marchName = culang.mainAntiScout;
						else
							t.report[reportId].marchName = culang.mainScout;
					} else if (rpt.marchType == 4) {
						if (t.report[reportId].sideId == 0)
							t.report[reportId].marchName = culang.mainDefense;
						else
							t.report[reportId].marchName = culang.mainAttack;
					} else if (rpt.marchType == 10 || rpt.marchType == 9) {
						t.report[reportId].marchName =  culang.mainAttack;
					} else
						t.report[reportId].marchName = '?';
					t.data.push ({
						reportId: reportId,
					});
				}
			}
			if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
				ById("idRptStatus").innerHTML = culang.reportSearchedPages+' ' + (parseInt(page)+1) + ' / ' + t.maxPages;
				t.getRpt(parseInt(page)+1);
				if (t.data.length > 0)
					t.DisplayRpt();
			} else if (page) {

				if (ById("KsSyntheseAttack").checked) {
					t.stopSearch ('<a id=KsresumeAT style="color:#ffaaaa" onclick="javascript:void(0);"><u>'+culang.reportAttackSummary+'</u></a>');
					setTimeout(function() {
						// ouverture du resume des rapports FS avec Items
						ById("KsresumeAT").addEventListener ('click', t.AfficheResumeAtk, false);
					}, 1000);
				} else {

					if (Options.rptType=='player') {
						t.stopSearch ('<a id=KsresumeDF style="color:#ffaaaa" onclick="javascript:void(0);"><u>'+culang.reportDarkForestSummary+'</u></a>');
						setTimeout(function() {
							// ouverture du resume des rapports FS avec Items
							ById("KsresumeDF").addEventListener ('click', t.AfficheResume, false);
						}, 1000);
					} else {
						t.stopSearch (''+culang.mainHDone+'');
					}
				}
			}
		}
	},
	AfficheResumeAtk:function() {
		var t = Tabs.Rpt;
		var puipui=new Array();
		var fortmight = {u53: "4",u55: "7",u60: "1",u61: "2",u62: "3",    };
		for (var ui = 1 ; ui<18; ui++)
			puipui.push(uW.unitmight['unt'+ui]);
		puipui[52] = fortmight['u53'];
		puipui[54] = fortmight['u55'];
		puipui[59] = fortmight['u60'];
		puipui[60] = fortmight['u61'];
		puipui[61] = fortmight['u62'];
		var messageBody="";
		reportsSearched = t.dataAT.length;
		reportsFound = 0;
		var tr0=0,tr1=0,tr2=0,tr3=0,tr4=0,tr5=0;
		if (reportsSearched>0) {
			messageBody +='<br><table width=98%><thead><th>'+culang.mainPlayer+'<br>'+uW.g_js_strings.commonstr.alliance+'</th><th><img src="'+IMGgold30+'"></th>\
	  <th><img src="'+IMGfood30+'"></th><th><img src="'+IMGwood30+'"></th>\
	  <th><img src="'+IMGstone30+'"></th><th><img src="'+IMGiron30+'"></th>\
	  <th><img src="'+IMGastone30+'"></th></thead><tbody>';
			t.dataAT.sort(function(a, b){
				var sortA=a.nom,sortB=b.nom;
				if (sortA < sortB) return -1
				if (sortA > sortB) return 1
				return 0
			});
			var datartp = [];
			var nbrp=0;
			for (var i=0; i<reportsSearched;i++) {
				var idrapport=t.dataAT[i].reportId;
				if ((t.what == '' || (t.dataAT[i].nom.search(t.what, "i") != -1)  || (t.dataAT[i].alliance.search(t.what, "i") != -1))
					&& (t.whatNot == '' || (t.dataAT[i].nom.search(t.whatNot, "i") != -1 && t.dataAT[i].alliance.search(t.whatNot, "i") != -1)))
				{

					if (datartp[nbrp]==undefined) {
						datartp[nbrp]=[];
						datartp[nbrp].nom = t.dataAT[i].nom;
						datartp[nbrp].alliance = t.dataAT[i].alliance;
						datartp[nbrp].res0=0;
						datartp[nbrp].res1=0;
						datartp[nbrp].res2=0;
						datartp[nbrp].res3=0;
						datartp[nbrp].res4=0;
						datartp[nbrp].res5=0;
						for (var z=1;z<64;z++) {
							datartp[nbrp]['s1unit'+z] =0;
							datartp[nbrp]['s0unit'+z] =0;
						}
					}
					if(datartp[nbrp].nom==t.dataAT[i].nom && datartp[nbrp].alliance==t.dataAT[i].alliance) {
						datartp[nbrp].res0 += parseIntNan(t.reportAT[idrapport].res0);
						datartp[nbrp].res1 += parseIntNan(t.reportAT[idrapport].res1);
						datartp[nbrp].res2 += parseIntNan(t.reportAT[idrapport].res2);
						datartp[nbrp].res3 += parseIntNan(t.reportAT[idrapport].res3);
						datartp[nbrp].res4 += parseIntNan(t.reportAT[idrapport].res4);
						datartp[nbrp].res5 += parseIntNan(t.reportAT[idrapport].res5);
						for (var z=1;z<64;z++) {
							datartp[nbrp]['s1unit'+z] += parseIntNan(t.reportAT[idrapport]['s1unit'+z]);
							datartp[nbrp]['s0unit'+z] += parseIntNan(t.reportAT[idrapport]['s0unit'+z]);
						}
					} else {
						nbrp++;
						datartp[nbrp]=[];
						datartp[nbrp].nom = t.dataAT[i].nom;
						datartp[nbrp].alliance = t.dataAT[i].alliance;
						datartp[nbrp].res0=0;
						datartp[nbrp].res1=0;
						datartp[nbrp].res2=0;
						datartp[nbrp].res3=0;
						datartp[nbrp].res4=0;
						datartp[nbrp].res5=0;
						datartp[nbrp].res0 += parseIntNan(t.reportAT[idrapport].res0);
						datartp[nbrp].res1 += parseIntNan(t.reportAT[idrapport].res1);
						datartp[nbrp].res2 += parseIntNan(t.reportAT[idrapport].res2);
						datartp[nbrp].res3 += parseIntNan(t.reportAT[idrapport].res3);
						datartp[nbrp].res4 += parseIntNan(t.reportAT[idrapport].res4);
						datartp[nbrp].res5 += parseIntNan(t.reportAT[idrapport].res5);
						for (var z=1;z<64;z++) {
							datartp[nbrp]['s1unit'+z] =0;
							datartp[nbrp]['s0unit'+z] =0;
							datartp[nbrp]['s1unit'+z] += parseIntNan(t.reportAT[idrapport]['s1unit'+z]);
							datartp[nbrp]['s0unit'+z] += parseIntNan(t.reportAT[idrapport]['s0unit'+z]);
						}
					}
				}// fin du regrouppement
			}
			reportsSearched = datartp.length;
			var tres=[0,0,0,0,0,0];
			var perts1=[];var perts0=[];
			for (var z=1;z<64;z++) { perts1[z]=0;perts0[z]=0; }

			for (var i=0; i<reportsSearched;i++) {
				messageBody += '<tr><td>'+datartp[i].nom+'<br>'+datartp[i].alliance+'</td>';
				for (var res=0;res<6;res++) {
					messageBody += '</td><td align=right>';
					var cb=0;
					if (datartp[i]["res"+res] != undefined) {
						cb=parseIntNan(datartp[i]["res"+res]);
						tres[res]+=cb;
					}
					messageBody += addCommas(cb);
				}
				for (var z=1;z<64;z++) {
					perts1[z]+=parseIntNan(datartp[i]['s1unit'+z]);
					perts0[z]+=parseIntNan(datartp[i]['s0unit'+z]);
				}
			}
			messageBody += '</td></tr><tr><td><b>'+culang.mainHTotal+': </td>';
			for (var res=0;res<6;res++) messageBody +='<td align=right><b>'+addCommas(tres[res])+'</b></td>';
			messageBody += "</tr></table>";
			messageBody += "<br><table><thead><th width=120><b>"+culang.reportOurLooses+"</b></th>";
			for (var z=1;z<64;z++) {
				if (perts1[z]>0) {
					messageBody +='<th width=6%><img height=20 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+z+'_30.jpg ';
					if(z<16)
						messageBody +='title="'+uW.unitcost['unt'+z][0]+'"';
					messageBody +='></th>';
				}
			}
			messageBody +='<th></th></thead><tr><td>'+culang.mainAmount+'</td>';
			for (var z=1;z<64;z++) if (perts1[z]>0) messageBody +='<td align=right>'+ addCommas(perts1[z])+'</td>';
			messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+'</td>';
			for (var z=1;z<64;z++) if (perts1[z]>0) messageBody +='<td align=right>'+ addCommas(parseIntNan(perts1[z])*parseIntNan(puipui[z-1]))+'</td>';
			var to1=0;
			messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+' total</td>';
			for (var z=1;z<64;z++) to1+=(parseIntNan(perts1[z])*parseIntNan(puipui[z-1]));
			messageBody += "<td align=right><b>"+addCommas(to1)+"</b></td></tr><thead><th><b>"+culang.reportEnemyLooses+"</b></th>";
			for (var z=1;z<64;z++) {
				if (perts0[z]>0) {
					messageBody +='<th width=6%><img height=20 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+z+'_30.jpg ';
					if(z<18)
						messageBody +='title="'+uW.unitcost['unt'+z][0]+'"';
					messageBody +='></th>';
				}
			}
			messageBody +='<th></th></thead><tr><td>'+culang.mainAmount+'</td>';
			for (var z=1;z<64;z++) if (perts0[z]>0)messageBody +='<td align=right>'+ addCommas(parseIntNan(perts0[z]))+'</td>';
			messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+'</td>';

			for (var z=1;z<64;z++) if (perts0[z]>0)messageBody +='<td align=right>'+ addCommas(parseIntNan(perts0[z])*parseIntNan(puipui[z-1]))+'</td>';
			var to2=0;
			messageBody +='</tr><tr><td>'+culang.reportTotalMight+'</td>';
			for (var z=1;z<64;z++) to2+= (parseIntNan(perts0[z])*parseIntNan(puipui[z-1]));
			messageBody +="<td align=right><b>"+addCommas(to2)+"</b></td></tr></table><br>";

			if (to1<to2)
				messageBody += "<br><b>"+culang.reportMightDifference+" <font color=#449944>"+addCommas((to2-to1))+"</font><br>";
			if (to1==to2)
				messageBody += "<br><b>"+culang.reportNoMightLoose+"<br>";
			if (to1>to2)
				messageBody += "<br><b>"+culang.reportMightDifference+" <font color=#994444>"+addCommas((to1-to2))+"</font><br>";

		} else {
			messageBody +="<br><center>"+culang.reportNoAttackSummary+"<br>";
		}
		t.popRapportAT = new CPopup('pbRapportATBody', 0, 0, 770, 500, true, function() {clearTimeout (1000);});
		t.popRapportAT.centerMe (mainPop.getMainDiv());
		var m = '<DIV style="max-height:465px;">';
		m+= messageBody + '</div>';
		t.popRapportAT.getMainDiv().innerHTML = m;
		t.popRapportAT.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.reportAttackSummaryHead+'</DIV>';
		t.popRapportAT.show(true);
	},
	AfficheResume:function() {
		var t = Tabs.Rpt;
		var messageBody="";
		reportsSearched = t.dataDF.length;
		reportsFound = 0;
		if (t.dataDF.length>0) {
			messageBody +='<br><center><table width=60%><thead><th>'+culang.mainReports+'</th><th>'+uW.g_js_strings.commonstr.level+'</th><th colspan=2>'+culang.mainItems+'</th></thead><tbody>';
			for (var i=0; i<reportsSearched;i++) {
				var idrapport=t.dataDF[i].reportId;
				var rpt =  t.reportDF[idrapport];
				messageBody += '<tr><td align=right><a onclick="getReport('+ idrapport+')">'+idrapport+'</A></td><td>'+rpt.lvl+'</td><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/' + rpt.item + '.jpg></td><td>'+uW.ksoItems[rpt.item].name+'</td></tr>';
			}
			messageBody += "</tbody></table>";
		} else {
			messageBody +="<br><center>"+culang.reportNoDarkForestReports+"</center><br>";
		}

		messageBody +='<br><input type=button value="'+culang.reportDeleteDarkForest+'" id=KsDelAllDF></center>';


		t.popRapportDF = new CPopup('pbRapportDFBody', 0, 0, 500, 400, true, function() {clearTimeout (1000);});
		t.popRapportDF.centerMe (mainPop.getMainDiv());

		var m = '<DIV style="max-height:365px;">';
		m+= messageBody + '</div>';
		t.popRapportDF.getMainDiv().innerHTML = m;
		t.popRapportDF.getTopDiv().innerHTML = '<DIV class="popupBanner"><B>'+culang.reportDarkForestSummaryHead+'</B></DIV>';
		t.popRapportDF.show(true);
		ById('KsDelAllDF').addEventListener ('click', t.DeleteRptDF, false);

	},
	pagesasup:0,
	DeleteRptDF:function() {
		var t = Tabs.Rpt;
		t.pagesasup = 0;
		t.fetchreport(0, t.checkreports);
		t.popRapportDF.show(false);
		t.popRapportDF.destroy();
		t.popRapportDF = null;
	},
	fetchreport : function(pageNo, callback){
		var t =  Tabs.Rpt;
		if (t.pagesasup>=t.maxPages) return;
		var params = uW.Object.clone(uW.g_ajaxparams);
		if(pageNo > 1)
			params.pageNo = pageNo;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/listReports.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				t.pagesasup++;
				callback(rslt);
			},
			onFailure: function () {
				t.pagesasup++;
				callback();
			},
		});
	},

	checkreports : function(rslt){
		var t = Tabs.Rpt;
		if(!rslt.ok){
			return;
		}
		if(rslt.arReports.length < 1){
			return;
		}
		var reports = rslt.arReports;
		var totalPages = rslt.totalPages;
		var deletes1 = new Array();
		for(k in reports){
			if(reports[k].side0TileType==54)
				deletes1.push(k.substr(2));

		}
		if(deletes1.length > 0 ){
			t.deleteCheckedReports(deletes1);
		} else {

			return;
		}
	},
	deleteCheckedReports : function(deletes1){
		var t =  Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.s1rids = deletes1.join(",");
		params.cityrids = '';
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/deleteCheckedReports.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if(rslt.ok){
					Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length);
				}
				t.fetchreport(0, t.checkreports);
				t.DisplayRpt();
			},
			onFailure: function () {
			},
		});
	},
	KsSyntheseAttack:function(reportId, sideId, lvl) {
		var t = Tabs.Rpt;
		var rpt = t.report[reportId];
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.rid=reportId;
		params.side=sideId;
		if (params.side > -1) {
			new AjaxRequest(uW.g_ajaxpath+"ajax/fetchReport.php"+uW.g_ajaxsuffix, {  method:"post",  parameters:params,

				onSuccess:function(msg){
					var rslt = eval("(" + msg.responseText + ")");
					if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
					t.dataAT.push ({reportId: reportId, nom:rpt.side0Name, alliance:rpt.side0AllianceName});
					t.reportAT[reportId] = [];
					t.reportAT[reportId].nom = rpt.side0Name;
					t.reportAT[reportId].alliance = rpt.side0AllianceName;
					t.reportAT[reportId].res0=0;
					t.reportAT[reportId].res1=0;
					t.reportAT[reportId].res2=0;
					t.reportAT[reportId].res3=0;
					t.reportAT[reportId].res4=0;
					t.reportAT[reportId].res5=0;
					if (rslt.loot) {
						if (rslt['loot'][0] !== undefined) t.reportAT[reportId].res0=rslt['loot'][0];
						if (rslt['loot'][1] !== undefined) t.reportAT[reportId].res1=rslt['loot'][1];
						if (rslt['loot'][2] !== undefined) t.reportAT[reportId].res2=rslt['loot'][2];
						if (rslt['loot'][3] !== undefined) t.reportAT[reportId].res3=rslt['loot'][3];
						if (rslt['loot'][4] !== undefined) t.reportAT[reportId].res4=rslt['loot'][4];
						if (rslt['loot'][6] !== undefined) t.reportAT[reportId].res5=rslt['loot'][6];
					}
					if (sideId==0) { // les pertes !!!!
						for (var zz=0;zz<6;zz++)
							t.reportAT[reportId]["res"+zz] = t.reportAT[reportId]["res"+zz] *-1;
					}
					if (rslt['fght'] != undefined){
						if (rslt['fght']["s1"] != undefined) {
							for (var i=1;i<18;i++) {
								if (rslt['fght']["s1"]['u'+i] != undefined) {
									if (sideId==1) t.reportAT[reportId]['s1unit'+i]=rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1]; // perte 
									else t.reportAT[reportId]['s0unit'+i]=rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1]; // perte 

								}else{
									if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
									else t.reportAT[reportId]['s0unit'+i]=0;
								}
							}
							for (var i=53;i<=55;i++) {
								if (rslt['fght']["s1"]['f'+i] != undefined) {
									if (sideId==1) t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
									else t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];

								}else{
									if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
									else t.reportAT[reportId]['s0unit'+i]=0;
								}
							}
							for (var i=60;i<=63;i++) {
								if (rslt['fght']["s1"]['f'+i] != undefined) {
									if (sideId==1) t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
									else t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];

								}else{
									if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
									else t.reportAT[reportId]['s0unit'+i]=0;
								}
							}
						}
						if (rslt['fght']["s0"] != undefined) {
							for (var i=1;i<18;i++) {
								if (rslt['fght']["s0"]['u'+i] != undefined) {
									if (sideId==1) {
										t.reportAT[reportId]['s0unit'+i]=rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1]; // perte
									}else{
										t.reportAT[reportId]['s1unit'+i]=rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1]; // perte
									}
								} else {
									if (sideId==1) {
										t.reportAT[reportId]['s0unit'+i]=0;
									} else {
										t.reportAT[reportId]['s1unit'+i]=0;
									}
								}
							}
							for (var i=53;i<=55;i++) {
								if (rslt['fght']["s0"]['f'+i] != undefined) {
									if (sideId==1) {
										t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
									} else {
										t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
									}
								}else{
									if (sideId==1) t.reportAT[reportId]['s0unit'+i]=0;
									else t.reportAT[reportId]['s1unit'+i]=0;
								}
							}
							for (var i=60;i<=63;i++) {
								if (rslt['fght']["s0"]['f'+i] != undefined) {
									if (sideId==1) {
										t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
									} else {
										t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
									}
								}else{
									if (sideId==1) {
										t.reportAT[reportId]['s0unit'+i]=0;
									} else {
										t.reportAT[reportId]['s1unit'+i]=0;
									}
								}
							}
						}
					}

				} });
		}
	},
	FindItemRpt:function(reportId, sideId, lvl) {
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.rid=reportId;
		params.side=sideId;
		if (params.side > -1) {
			new AjaxRequest(uW.g_ajaxpath+"ajax/fetchReport.php"+uW.g_ajaxsuffix, {  method:"post",  parameters:params,

				onSuccess:function(msg){
					var rslt = eval("(" + msg.responseText + ")");
					if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
					if (rslt.loot) {
						if (rslt['loot'][5] !== undefined) {
							var q=uW.Object.keys(rslt['loot'][5]);
							if (q.length>0) {
								for(var u=0,y=q.length;u<y;++u){
									C=q[u];
									if (uW.ksoItems[C]!==undefined) {
										t.dataDF.push ({reportId: reportId,});
										t.reportDF[reportId] = [];
										t.reportDF[reportId].lvl = lvl;
										t.reportDF[reportId].item = C;
									}
								}
							}


						}

					}
				}
			});
		}

	},
	DisplayMail: function (){
		var t = Tabs.Rpt;
		var results = ById("idBoRptResultsDiv");
		if(!t.data.length) {
			results.innerHTML = '<center><i><b>'+culang.reportNoResults+'</b></i></center>';
			return;
		}
		reportsSearched = t.data.length;
		reportsFound = 0;
		t.content = '';
		for (var i=0; i<reportsSearched;i++) {
			var rpt = t.data[i];
			if ((t.what == '' || (rpt.subject.search(t.what, "i") != -1) || (rpt.displayName.search(t.what, "i") != -1))
				&& (t.whatNot == '' || ((rpt.subject.search(t.whatNot, "i") == -1) && (rpt.displayName.search(t.whatNot, "i") == -1)))) {
				if (rpt.subject == '')
					rpt.subject = ''+culang.mainNoSubject+'';
				reportsFound++;
				if (reportsFound == 1)
					t.content += '<center><table width=97%><thead><th title="'+culang.mainPage+'"><b><u>'+culang.shortPage+'</u></b></th><th><b><u>'+culang.mainDate+'</u></b></th><th><b><u>'+culang.mainFrom+'</u></b></th><th><b><u>'+culang.mainSubject+'</u></b></th><th><b><u>'+culang.mainDelete+'</u></b></th></thead><tbody>';
				var stylee="";
				if (rpt.messageRead==0) stylee=' style="background-color:#CCCCCC;"';
				t.content += '<tr><td align=right '+stylee+'>'+rpt.page+'</td><td '+stylee+'>'+rpt.dateSent+'</td><td '+stylee+'>'+rpt.displayName+'</td>';
				t.content += '<td '+stylee+'><A><SPAN onclick="getmsg('+ rpt.messageId +')">' + rpt.subject + '</SPAN></a></td><td><a onclick="DelMail('+ rpt.messageId +');"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteMessageNote+'" alt="'+culang.mainDelete+'"></a></td></tr>';
			}
		}
		if (reportsFound > 1)
			t.content += '</tbody></table></center>';
		if (reportsFound == 0 && reportsSearched > 0)
			t.content = '<center><i><b>'+culang.reportNoResults+'</b></i></center>';
		results.innerHTML = t.content;
		ById("idRptSearched").innerHTML = '&nbsp;'+culang.reportSearched+' ' + reportsSearched;
		ById("idRptFound").innerHTML = ''+culang.reportFound+' ' + reportsFound;
	},

	getMailBody: function(ID,dataI){
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.messageId=ID;
		params.requestType="GET_MESSAGE_FOR_ID";

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok)
					t.displayMailBody(rslt.messageBody, ID);
			},
			onFailure: function () {},
		}, false);
	},

	displayMailBody: function (messageBody, ID) {
		var t = Tabs.Rpt;
		if (t.popMsg == null) {
			t.popMsg = new CPopup('pbMailBody', 0, 0, 670, 500, true, function() {clearTimeout (1000);});
			t.popMsg.centerMe (mainPop.getMainDiv());
		}
		messageBody=messageBody.replace(/custom-line-break/g,"<br>");
		var m = '<DIV style="max-height:465px;"><br><hr>';
		m+= messageBody + '<hr><a onclick="DelMail('+ ID +');"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteMessageNote+'" alt="'+culang.mainDelete+'"></a><br></div>';
		t.popMsg.getMainDiv().innerHTML = m;
		t.popMsg.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.mainMessage+'</DIV>';
		t.popMsg.show(true);
	},

	DisplayRpt: function (){
		var t = Tabs.Rpt;
		var results = ById("idBoRptResultsDiv");
		if(!t.data.length) {
			results.innerHTML = '<center><i><b>'+culang.reportNoResults+'</b></i></center>';
			return;
		}
		var myAllianceId = parseInt(getMyAlliance()[0]);
		reportsSearched = t.data.length;
		reportsFound = 0;
		t.content = '';
		for (var i=0; i<reportsSearched;i++) {
			var reportId = t.data[i].reportId;
			var rpt = t.report[reportId];
			if ((rpt.side0Name=='undefined') && (rpt.marchName != ''+culang.mainDesertion+''))
				continue;
			if ((((myAllianceId == parseInt(rpt.side1AllianceId) && Options.arAttacker != 'Them')
				|| (myAllianceId != parseInt(rpt.side1AllianceId) && Options.arAttacker != 'Us')
				|| Options.arAttacker == 'Both')
				&& ((myAllianceId == parseInt(rpt.side0AllianceId) && Options.arTarget != 'Them')
				|| (myAllianceId != parseInt(rpt.side0AllianceId) && Options.arTarget != 'Us')
				|| Options.arTarget == 'Both')
				&& ((Options.arAttack && (rpt.marchName ==  ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+''))
				|| (Options.arScout && (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainScout+''))
				|| (Options.arReinforce && rpt.marchName == ''+culang.mainReinforced+'')
				|| (Options.arTransport && rpt.marchName == ''+culang.mainTransport+'')))
				|| (rpt.marchName == ''+culang.mainDesertion+'')) {
				if (((t.what == ''
					|| (rpt.side1Name.search(t.what, "i") != -1)
					|| (rpt.side1AllianceName.search(t.what, "i") != -1)
					|| (rpt.side0Name.search(t.what, "i") != -1)
					|| (rpt.side0AllianceName.search(t.what, "i") != -1)
					|| (rpt.side0TileTypeText.search(t.what, "i") != -1))
					&& (t.whatNot == ''
					|| ((rpt.side1Name.search(t.whatNot, "i") == -1)
					&& (rpt.side1AllianceName.search(t.whatNot, "i") == -1)
					&& (rpt.side0Name.search(t.whatNot, "i") == -1)
					&& (rpt.side0AllianceName.search(t.whatNot, "i") == -1)
					&& (rpt.side0TileTypeText.search(t.whatNot, "i") == -1))))
					|| (rpt.marchName == ''+culang.mainDesertion+'')) {

					if ((ById("idRptFiltre1").value=="") ||   (rpt.side0TileType==54 && ById("idRptFiltre1").value==54)  ||
						(rpt.side0TileType>0 && rpt.side0TileType<51 && ById("idRptFiltre1").value==0)) {


						reportsFound++;
						if (reportsFound == 1) {
							t.content += '<center><table class=pdxTabOverview width=100% cellspacing=0 cellpadding=3><thead><th title="'+culang.mainPage+'"><b><u>'+culang.shortPage+'</u></b></th><th title="'+culang.mainAction+'"><b><u>'+culang.shortAction+'</u></b></th><th><b><u>'+culang.mainDate+'</u></b></th><th><b><u>'+culang.mainAttacker+'</u></b></th><th><b><u>'+culang.shortCoordinate+'</u></b></th>';
							if (Options.arAttacker != 'Us')
								t.content += '<th><b><u>'+uW.g_js_strings.commonstr.alliance+'</u></b></th>';
							t.content += '<th><b><u>'+culang.reportMarchType+'</u></b></th><th><b><u>'+culang.mainTarget+'</u></b></th><th><b><u>'+culang.shortCoordinate+'</u></b></th>';
							if (Options.arTarget != 'Us')
								t.content += '<th><b><u>'+uW.g_js_strings.commonstr.alliance+'</u></b></th>';
							t.content += '<th><b><u>'+culang.mainType+'</u></b></th><th><span title="'+culang.reportNextCity+'"><b><u>'+culang.mainSRallyPoint+'</u></b></span></th><th><span title="'+culang.reportShortDistanceNote+'"><b><u>'+culang.reportShortDistance+'</u></b></span></th></thead><tbody>';
						}


						var closestDist=999999;
						var closestLoc=null;
						var closestNum=1;
						for (var c=0; c<Cities.numCities; c++){
							var city = Cities.cities[c];
							var dist=distance(city.x,city.y,rpt.side0XCoord,rpt.side0YCoord);
							if(dist<closestDist) {
								closestDist=dist;
								closestLoc=city.x +','+ city.y;
								closestNum=c+1;
							}
						}
						if (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainDefense+'')
							style=' style="background-color:#EF9999;"';
						else if (rpt.marchName == ''+culang.mainReinforced+'')
							style=' style="background-color:#99EF99;"';
						else
							style="";
						t.content += '<tr id="Ksrpt'+ reportId +'"><td align=right '+style+'>'+rpt.page+'</td><td  align=right '+style+'><a onclick="getReport('+ reportId+')"><img  border=0 src="'+IMGshowButton+'" title="'+culang.mainShow+'"></a>';
						if (rpt.side0Name==Seed.player.name || rpt.side1Name==Seed.player.name) {
							t.content +='&nbsp;<a onclick="DelReport('+ reportId +', false);document.getElementById(\'Ksrpt'+ reportId +'\').style.display=\'none\';"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteNowNote+'"></a>';
						}
						t.content += '</td><td '+style+'>'+formatDate(rpt.reportUnixTime,DATETIME_STR)+'</td>';
						if (rpt.marchName == ''+culang.mainDesertion+'') {
							t.content += '<td '+style+'></td><td '+style+'></td>';
							if (Options.arAttacker != 'Us')
								t.content += '<td '+style+'></td>';
							t.content += '<td '+style+'>'+rpt.marchName+'</td><td '+style+'></td><td '+style+'></td><td '+style+'></td>';
							if (Options.arAttacker != 'Us')
								t.content += '<td '+style+'></td>';
							t.content += '<td '+style+'></td><td '+style+'></td>';
						} else {
							t.content += '<td '+style+'><span title="'+rpt.side1Name+'">'+rpt.side1Name.substring(0,12)+'</span></td><td align=center '+style+'><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a></td>';
							if (Options.arAttacker != 'Us')
								t.content += '<td '+style+'><span title="'+rpt.side1AllianceName+'">'+rpt.side1AllianceName.substring(0,17)+'</span></td>';
							if (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainScout+'')
								t.content += '<TD '+style+'><FONT color="black">'+rpt.marchName+'</font></td>';
							else if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
								t.content += '<TD '+style+'><FONT color="black">'+rpt.marchName+'</font></td>';
							else if (rpt.marchName == ''+culang.mainReinforced+'')
								t.content += '<TD '+style+'><FONT color="black">'+rpt.marchName+'</font></td>';
							else
								t.content += '<TD '+style+'>'+rpt.marchName+'</td>';
							//t.content += '<td>'+rpt.marchName+'</td>';
							t.content += '<td '+style+'><span title="'+rpt.side0Name+'">'+rpt.side0Name.substring(0,12)+'</span></td>';
							t.content += '<td align=center '+style+'><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a></td>';
							if (Options.arTarget != 'Us')
								t.content += '<td '+style+'><span title="'+rpt.side0AllianceName+'">'+rpt.side0AllianceName.substring(0,17)+'</span></td>';
							t.content += '<td '+style+'>'+rpt.side0TileTypeLevel+'</td><td align=center '+style+'><A onclick=\"citysel_click(document.getElementById(\'citysel_'+ (closestNum)+'\'));\">' + closestLoc + '</a></td><td align=right '+style+'>'+Math.floor(closestDist)+'</td></tr>';
						}
					}
				}
			}
		}
		if (reportsFound > 1)
			t.content += '</tbody></table></center>';
		if (reportsFound == 0 && reportsSearched > 0)
			t.content = '<center><b><i>'+culang.reportNoResults+'</i></b></center>';
		results.innerHTML = t.content;
		ById("idRptSearched").innerHTML = '&nbsp;'+culang.reportSearched+' ' + reportsSearched;
		ById("idRptFound").innerHTML = ''+culang.reportFound+' ' + reportsFound;
		//Chatausgabe wenn AutoScan aktiviert
		if (Options.reportScanner.start) {
			for (var i=0; i<reportsSearched;i++) {
				var reportId = t.data[i].reportId;
				var rpt = t.report[reportId];
				if (rpt.side0Name == 'undefined') continue;
				if (LastUnixTime >= rpt.reportUnixTime) continue;
				if (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainDefense+'') {
					//'BERICHT auf Seite {page} / Typ: {type} / Zeit: {time} / {attacker} / {member} braucht evtl. Hilfe / Bericht: {report}';
					var rep = {
						'page'     : rpt.page,
						'type'     : rpt.marchName,
						'time'     : formatDate(rpt.reportUnixTime,DATETIME_STR),
						'attacker' : rpt.side1Name + ' (' + rpt.side1XCoord + ',' + rpt.side1YCoord + ') ' + rpt.side1AllianceName,
						'member'   : rpt.side0Name + ' (' + rpt.side0XCoord + ',' + rpt.side0YCoord + ')',
						'report'   : '#' + reportId + '#',
					};
					var msg = culang.reportScannerChatMsg.mreplace(rep);
					if (Options.reportScanner.lastmsg != rpt.reportUnixTime) sendChat("/a " + msg);
					Options.reportScanner.lastmsg = rpt.reportUnixTime;
					LastUnixTime = rpt.reportUnixTime;
				}
			}
			saveOptions();
		}
	},

	getReportBody: function(reportId){
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.rid=parseInt(reportId);
		params.side=t.report[reportId].sideId;
		if (params.side > -1) {
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchReport.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					t.displayReportBody(rslt,reportId);
				},
				onFailure: function (rslt) {},
			}, false);
		} else {

		}
	},

	getReportBodyAC : function(rpId) {
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
			params.rid=rpId;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchReport.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					var rpt = rslt['index'];
					rpt.Side0PlayerId = rslt['index']['side0PlayerId'];
					rpt.Side0AllianceId = rslt['index']['side0AllianceId'];
					rpt.Side1PlayerId = rslt['index']['side1PlayerId'];
					if (rpt.marchType == 0)
						rpt.marchName = culang.mainDesertion;
					else if (rpt.marchType == 1)
						rpt.marchName = culang.mainTransport;
					else if (rpt.marchType == 2)
						rpt.marchName = culang.mainReinforced;
					else if (rpt.marchType == 3 || rpt.marchType == 11) {
						if (rpt.sideId == 0)
							rpt.marchName = culang.mainAntiScout;
						else
							rpt.marchName = culang.mainScout;
					} else if (rpt.marchType == 4) {
						if (rpt.sideId == 0)
							rpt.marchName = culang.mainDefense;
						else
							rpt.marchName = culang.mainAttack;
					} else if (rpt.marchType == 10 || rpt.marchType == 9) {
						rpt.marchName =  culang.mainAttack;
					} else
						rpt.marchName = '?';
						
					if (parseInt(rpt.side0TileType) == 10)
						rpt.side0TileTypeText=culang.kocGrassland;
					else if (parseInt(rpt.side0TileType) == 11)
						rpt.side0TileTypeText=culang.kocLake;
					else if (parseInt(rpt.side0TileType) == 20)
						rpt.side0TileTypeText=culang.kocForests;
					else if (parseInt(rpt.side0TileType) == 30)
						rpt.side0TileTypeText=culang.kocHill;
					else if (parseInt(rpt.side0TileType) == 40)
						rpt.side0TileTypeText=culang.kocMount;
					else if (parseInt(rpt.side0TileType) == 50)
						rpt.side0TileTypeText=culang.kocPlain;
					else if (parseInt(rpt.side0TileType) == 51 && parseInt(rpt.side0CityId) == 0)
						rpt.side0TileTypeText=culang.mainCity;
					else if (parseInt(rpt.side0TileType) == 54)
						rpt.side0TileTypeText=culang.shortDarkForest;
					else if (parseInt(rpt.side0CityId) == 0)
						rpt.side0TileTypeText=culang.kocShortBarbarian;
					else
						rpt.side0TileTypeText=culang.mainCity;

					t.GetNames(rpId,rpt);
				},
				onFailure: function () {
					alert('kabam is having issues');
				},
			}, false);
	},


	GetNames : function(rpId,rpt) {
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
			params.uid=rpt.Side0PlayerId;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/getUserGeneralInfo.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					rpt.side0Name = rslt['userInfo']['0']['name'];
					var params = uW.Object.clone(uW.g_ajaxparams);
						params.uid=rpt.Side1PlayerId;
						new MyAjaxRequest(uW.g_ajaxpath + "ajax/getUserGeneralInfo.php" + uW.g_ajaxsuffix, {
							method: "post",
							parameters: params,
							onSuccess: function (rslt) {
								rpt.side1Name = rslt['userInfo']['0']['name'];
								t.GetReport(rpId,rpt);					
							},
							onFailure: function () {
								alert('kabam is having issues');
							},
						}, false);
				},					
				onFailure: function () {
					alert('kabam is having issues');
				},
			}, false);
	},

	GetReport: function(rpId, rpt){
		var t = Tabs.Rpt;
		var params = uW.Object.clone(uW.g_ajaxparams);
		if (parseInt(rpt.side0AllianceId) == parseInt(Seed.allianceDiplomacies.allianceId)) {
			params.side = 0;
		} else {
			params.side = 1;
		}
		params.rid=rpId;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchReport.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					if(rslt.error_code)
						alert('found report but kabam would not let me see it');
					else {
						t.displayReportBody(rslt, rpId, rpt);
					}
				},
				onFailure: function (rslt) {
					
				},
			}, false);
	},
	
	displayReportBody: function (rslt, reportId, rpt) {
		var t = Tabs.Rpt;
		var popReport = null;
		if (rpt == null) var rpt = t.report[reportId];
		var m = '';
		var fortmight = {u53: "4",u55: "7",u60: "1",u61: "2",u62: "3",    };
		var unitImg = [];
		var puipui=new Array();
		for (var ui = 1 ; ui<18; ui++)
			puipui.push(uW.unitmight['unt'+ui]);
		puipui[53] = fortmight['u53'];
		puipui[55] = fortmight['u55'];
		puipui[60] = fortmight['u60'];
		puipui[61] = fortmight['u61'];
		puipui[62] = fortmight['u62'];
		ordre_grandeur=0;
		delta_perte=0;
		var perte_atk = 0;
		var perte_def = 0;
		for (var i=1;i<18;i++)
			unitImg[i] = '<img height=20 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg title="'+uW.unitcost['unt'+i][0]+'"></TD><TD>' + uW.unitcost['unt'+i][0].substr(0,10);
		for (var i=101;i<111;i++)
			unitImg[i] = '<img height=20 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg title="'+uW.g_js_strings.monsterUnitsNames['m'+i]+'"></TD><TD>' + uW.g_js_strings.monsterUnitsNames['m'+i].substr(0,10);
		unitImg[53] = '<img height=20 src="'+IMGmiddleCrossbows+'"></TD><TD>'+ uW.fortcost.frt53[0];
		unitImg[55] = '<img height=20 src="'+IMGmiddleTrebuchet+'"></TD><TD>'+ uW.fortcost.frt55[0];
		unitImg[60] = '<img height=20 src="'+IMGmiddleTrap+'"></TD><TD>'+ uW.fortcost.frt60[0];
		unitImg[61] = '<img height=20 src="'+IMGmiddleCaltr+'"></TD><TD>'+ uW.fortcost.frt61[0];
		unitImg[62] = '<img height=20 src="'+IMGmiddleSpiked+'"></TD><TD>' + uW.fortcost.frt62[0];
		goldImg = '<img src="'+IMGgold30+'"></TD><TD>' + uW.g_js_strings.commonstr.gold;
		foodImg = '<img src="'+IMGfood30+'"></TD><TD>' + uW.g_js_strings.commonstr.food;
		woodImg = '<img src="'+IMGwood30+'"></TD><TD>' + uW.g_js_strings.commonstr.wood;
		stoneImg = '<img src="'+IMGstone30+'"></TD><TD>' + uW.g_js_strings.commonstr.stone;
		oreImg = '<img src="'+IMGiron30+'"></TD><TD>' + uW.g_js_strings.commonstr.ore;
		aetherstoneImg = '<img src="'+IMGastone30+'"></TD><TD>'+ uW.g_js_strings.commonstr.aetherstone;

		function buildHeader () {
			var h='<TABLE class=pdxTab width=100%>';
			h+='<TR valign=top><TD align=left width=10%><B>';
			if (rpt.marchName == ''+culang.mainAntiScout+'')
				h+=''+culang.reportAntiScout+' ';
			else if (rpt.marchName == ''+culang.mainScout+'')
				h+=uW.g_js_strings.modal_messages_viewreports_view.scoutrpt+' ';
			else if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
				h+=uW.g_js_strings.modal_messages_viewreports_view.battleat+' ';

			else if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'')
				h+=rpt.marchName+' <u>'+culang.mainFrom+'</u><BR />'+rpt.marchName+' <u>'+culang.mainTo+'</u></B>';
			else if (rpt.marchName == ''+culang.mainTransport+'')
				h+=rpt.marchName+' <u>'+culang.mainFrom+'</u><BR />'+uW.g_js_strings.modal_messages_viewreports_view.transpto+'</B>';
			if (rpt.side0TileTypeText == ''+culang.kocShortBarbarian+'')
				h+=' '+culang.kocBarbarianCamps+' '+uW.g_js_strings.commonstr.level+' ' + rpt.side0TileLevel;
			else if (rpt.side0TileTypeText != ''+culang.mainCity+'')
				h+=' '+rpt.side0TileTypeText+' '+uW.g_js_strings.commonstr.level+' '+ rpt.side0TileLevel+' ';
			h+='</B>';
			if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'' || rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainScout+'')
				if (rslt['displayGlory']!==undefined)
					h+='<br><B>'+uW.g_js_strings.commonstr.glory+': <font color=red>'+rslt['glory']+'</font></B>';

			h+='</td>';
			if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'') {
				h+='<TD align=left width=1%>';
				if (Seed.player.name != rpt.side1Name)
					h+=rpt.side1Name;
				if (Seed.player.name != rpt.side0Name)
					h+='<BR />'+rpt.side0Name;
				h+='</TD>';
			}
			h+='<TD align=left width=5%>';

			if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'')
				h+='<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a><BR />';
			h+='<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a></TD>';

			if (rpt.side0TileTypeText != ''+culang.mainCity+'' && rpt.side0TileTypeText != ''+culang.kocShortBarbarian+'' && (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')) {
				if (rslt['conquered']==1)
					h+='<TD><FONT color="#CC0000"><B>'+uW.g_js_strings.commonstr.conquered+'</B></font></td>';
				else if (rslt['conquered']==0)
					h+='<TD><FONT color="#66CC33"><B>'+culang.mainSecured+'</B></font></td>';
			} else if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'') {
				h+='<TD align=left width=5%>'+rpt.side1CityName+'<BR />';
				if (rpt.side0CityName != '')
					h+=rpt.side0CityName+'</TD>';
				else
					h+=rpt.side0TileTypeText+' '+uW.g_js_strings.commonstr.level+' '+ rpt.side0TileLevel+'</TD>';
			}

			h+='<TD align=right>' + formatUnixTime(rpt.reportUnixTime,'24hour') + '<BR />&nbsp;';
			if (rpt.side0Name==Seed.player.name || rpt.side1Name==Seed.player.name)
				h+='<a onclick="DelReport('+ reportId +', false);ById(\'Ksrpt'+ reportId +'\').style.display=\'none\';ById(\'pbShowOther_X\').click();"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteNowNote+'"></a>';

			h+='&nbsp;'+uW.g_js_strings.modal_messages_viewreports_view.reportno+' ' + reportId + '</TD></TR></TABLE>';
			return h;
		}

		function handleunts () { // Troops sent to Reinforce or troops found on a Scout
			var hunts = '', th = '', tc = '', tf = '';
			if (rslt['unts'] != undefined) {
				if (rpt.marchName == ''+culang.mainReinforced+'')
					th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+culang.reportReinforcement+'</TH></TR>';
				else if (rslt['unts']['u1'] != undefined || rslt['unts']['u2'] != undefined || rslt['unts']['u3'] != undefined || rslt['unts']['u4'] != undefined || rslt['unts']['u5'] != undefined || rslt['unts']['u6'] != undefined || rslt['unts']['u7'] != undefined || rslt['unts']['u8'] != undefined || rslt['unts']['u9'] != undefined || rslt['unts']['u10'] != undefined || rslt['unts']['u11'] != undefined || rslt['unts']['u12'] != undefined)
					th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.troops+'</TH></TR>';
				for (var i=1;i<18;i++)
					if (rslt['unts']['u'+i] != undefined)
						tc+='<TR><TD>' + unitImg[i] + '</TD><TD align=right>'+addCommas(rslt['unts']['u'+i])+'</TD></TR>';

				tf='</TABLE>';
			}
			if (tc != '')
				hunts = th + tc + tf;
			return hunts;
		}

		function handlersc () { // Resources brought with reinforcements or found on a Scout
			var hrsc = '', th = '', tc = '', tf = '';
			if (rslt['rsc'] != undefined) {
				if (rslt['rsc']['r1'] > 0 || rslt['rsc']['r2'] > 0 || rslt['rsc']['r3'] > 0 || rslt['rsc']['r4'] > 0) {
					if (rpt.marchName == ''+culang.mainReinforced+'')
						th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.resources+'</TH></TR>';
					else {
						th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.resources+'</TH></TR>';
						if (rslt['gld'] > 0)
							tc+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommasInt(rslt['gld'])+'</TD></TR>';
					}
					if (rslt['rsc']['r1'] > 0)
						tc+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r1'])+'</TD></TR>';
					if (rslt['rsc']['r2'] > 0)
						tc+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r2'])+'</TD></TR>';
					if (rslt['rsc']['r3'] > 0)
						tc+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r3'])+'</TD></TR>';
					if (rslt['rsc']['r4'] > 0)
						tc+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r4'])+'</TD></TR>';
					tf='</TABLE>';
				}
			}
			if (tc != '')
				hrsc = th + tc + tf;
			return hrsc;
		}

		function handlefrt () { // Fortifications found on a Scout
			var hfrt = '', th = '', tc = '', tf = '';
			if (rslt['frt'] != undefined) {
				if (rslt['frt']['f53'] != undefined || rslt['frt']['f55'] != undefined || rslt['frt']['f60'] != undefined || rslt['frt']['f61'] != undefined || rslt['frt']['f62'] != undefined) {
					th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.modal_openWalls.walldef+'</TH></TR>';
					if (rslt['frt']['f53'] != undefined)
						tc+='<TR><TD>' + unitImg[53] + '</TD><TD align=right>'+addCommas(rslt['frt']['f53'])+'</TD></TR>';
					if (rslt['frt']['f55'] != undefined)
						tc+='<TR><TD>' + unitImg[55] + '</TD><TD align=right>'+addCommas(rslt['frt']['f55'])+'</TD></TR>';
					if (rslt['frt']['f60'] != undefined)
						tc+='<TR><TD>' + unitImg[60] + '</TD><TD align=right>'+addCommas(rslt['frt']['f60'])+'</TD></TR>';
					if (rslt['frt']['f61'] != undefined)
						tc+='<TR><TD>' + unitImg[61] + '</TD><TD align=right>'+addCommas(rslt['frt']['f61'])+'</TD></TR>';
					if (rslt['frt']['f62'] != undefined)
						tc+='<TR><TD>' + unitImg[62] + '</TD><TD align=right>'+addCommas(rslt['frt']['f62'])+'</TD></TR>';
					tf='</TABLE>';
				}
			}
			if (tc != '')
				hfrt = th + tc + tf;
			return hfrt;
		}

		function handleblds (bType) {
			if (rslt['blds'] != undefined) {

				var blds = rslt['blds']['b'+bType];
				var couleur='';
				if (bType==8) couleur=' style="background-color:red"';
				b = '<TR><TD '+couleur+'>'; arField = [], firstbld = true;
				b+=uW.buildingcost["bdg"+bType][0]+'</TD><TD '+couleur+'>';
				for (var i=1; i<12; i++)
					arField[i]=0;
				for (var i=0; i < blds.length; i++)
					arField[blds[i]]++
				for (var i=11; i>0; i--) {
					if (arField[i] > 0) {
						if (firstbld)
							firstbld = false;
						else
							b+=', ';
						if (arField[i] > 1)
							b+=arField[i] + ' x ';
						b+=' ' + i;
					}
				}
				b+='</TD></TR>';
			} else {
				b='';
			}
			return b;
		}

		if (t.popReport == null) {
			if (rpt.marchName == ''+culang.mainReinforced+'') {
				t.popReport = new CPopup('pbShowRein', 0, 0, 700, 600, true, function() {clearTimeout (1000);});
				m+= '<DIV style="max-height:285px">';
			} else if (rpt.marchName == ''+culang.mainTransport+'') {
				t.popReport = new CPopup('pbShowTrans', 0, 0, 700, 600, true, function() {clearTimeout (1000);});
				m+= '<DIV style="max-height:185px">';
			} else if (rpt.marchName == ''+culang.mainScout+'' && rslt['winner']==1 && rpt.sideId==1){
				t.popReport = new CPopup('pbShowOther', 0, 0, 700, 600, true, function() {clearTimeout (1000);});
				m+= '<DIV style="max-height:485px; ">';
			} else {
				t.popReport = new CPopup('pbShowOther', 0, 0, 700, 600, true, function() {clearTimeout (1000);});
				m+= '<DIV style="max-height:423px; ">';
			}
			t.popReport.centerMe (mainPop.getMainDiv());
			t.popReport.autoHeight (true);
		}
		m+=buildHeader();

		if (rpt.marchName == ''+culang.mainTransport+'') { // Transport
			m+='<TABLE class=pdxTab>'; // Only transports have these in rslt, so handle them here
			if (parseInt(rslt['gold']) > 0)
				m+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommas(rslt['gold'])+'</TD></TR>';
			if (parseInt(rslt['resource1']) > 0)
				m+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommas(rslt['resource1'])+'</TD></TR>';
			if (parseInt(rslt['resource2']) > 0)
				m+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommas(rslt['resource2'])+'</TD></TR>';
			if (parseInt(rslt['resource3']) > 0)
				m+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommas(rslt['resource3'])+'</TD></TR>';
			if (parseInt(rslt['resource4']) > 0)
				m+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommas(rslt['resource4'])+'</TD></TR>';
			if (parseInt(rslt['resource5'])> 0)
				m+='<TR><TD>'+aetherstoneImg+'</TD><TD align=right>'+addCommas(rslt['resource5'])+'</TD></TR>';
			m+='</TABLE>';
		}

		m+='<TABLE class=pdxTab>';
		if ((rslt['winner']==1 && rpt.sideId==0) || (rslt['winner']==0 && rpt.sideId==1)) {
			if (rpt.marchName == ''+culang.mainScout+'')
				m+='<TR><TD><FONT color="#CC0000"><B>'+uW.g_js_strings.modal_messages_viewreports_view.scoutfail+'</B></font></TD></TR>';
			else
				m+='<TR><TD><FONT color="#CC0000"><B>'+uW.g_js_strings.commonstr.defeat+'</B></font></TD></TR>';
		}
		if (rslt['winner']==0 && rpt.sideId==0)
			m+='<TR><TD><FONT color="#66CC33"><B>'+uW.g_js_strings.commonstr.victory+' !</B></font></TD></TR>';
		if (rslt['winner']==1 && rpt.sideId==1)
			m+='<TR><TD><FONT color="#66BB33"><B>'+uW.g_js_strings.commonstr.victory+' !</B></font></TD></TR>';

		if (rslt['wall'] != undefined) {


			if (rslt['wall'] > 0 && rslt['wall'] < 100)
				m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.wallbreach+' '+rslt['wall']+' '+uW.g_js_strings.modal_messages_viewreports_view.percdamage+'</TD></TR>';
			else
				m+='<TR><TD>'+ uW.g_js_strings.modal_messages_viewreports_view.wallbreach+'</TD></TR>';
		}
		m+= '</TABLE><BR />';
		if (rslt['wonGloryItem']) {
			m+="<TABLE class=pdxTab><TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/" + rslt['wonGloryItem'] + ".jpg></td><td colspan=2>"+uW.ksoItems[rslt['wonGloryItem']].name+"</td></tr></TABLE><BR />";
		}
		//Throne
		if (rslt['throneRoomDrop']) {
			var A=rslt['throneRoomDrop'];
			faction=A.faction;
			if (uW.kocThroneItems[rslt['throneRoomDrop'].id]) {
				var name=uW.kocThroneItems[rslt['throneRoomDrop'].id].name;

				m+="<TABLE class=pdxTab><TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+faction.replace('briton','britton')+"/"+faction.replace('briton','britton')+"_"+A.type+"_normal_1.png></td><td colspan=2>"+name+"</td></tr></TABLE><BR />";
			}
		}

		if (rslt['loot'] != undefined) {
			m+='<TABLE class=pdxTab>';
			if (rslt['loot'][0] > 0)
				m+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommas(rslt['loot'][0])+'</TD></TR>';
			if (rslt['loot'][1] > 0)
				m+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommas(rslt['loot'][1])+'</TD></TR>';
			if (rslt['loot'][2] > 0)
				m+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommas(rslt['loot'][2])+'</TD></TR>';
			if (rslt['loot'][3] > 0)
				m+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommas(rslt['loot'][3])+'</TD></TR>';
			if (rslt['loot'][4] > 0)
				m+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommas(rslt['loot'][4])+'</TD></TR>';
			if (rslt['loot'][6] > 0)
				m+='<TR><TD>'+aetherstoneImg+'</TD><TD align=right>'+addCommas(rslt['loot'][6])+'</TD></TR>';
			if (rslt['loot'][5] !== undefined) {
				var q=uW.Object.keys(rslt['loot'][5]);
				if (q.length>0) {
					for(var u=0,y=q.length;u<y;++u){
						C=q[u];
						if (uW.ksoItems[C]!==undefined)
							m+="<TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/" + C + ".jpg></td><td colspan=2>"+uW.ksoItems[C].name+"</td></tr>";
					}
				}

			}

			m+='</TABLE><BR />';
		}

		if (rpt.marchName == ''+culang.mainReinforced+'') {
			m+=handleunts();
			m+=handlersc();
		}

		if (rpt.marchName == ''+culang.mainScout+'' && rslt['winner']==1) {
			m+='<TABLE class=pdxTab width=100%><TR><TD width=50% align=left valign=top>';
			m+=handleunts();
			if (rpt.side0TileTypeText!=''+culang.shortDarkForest+'')  m+=handlefrt();
			m+=handlersc();
			m+='</TD><TD width=50% align=left valign=top>';
			if (rpt.side0TileTypeText!=''+culang.shortDarkForest+'') {
				m+='<TABLE class=pdxTab width=100%>';
				if (rslt['lstlgn'] != undefined) {
					if (!rslt['lstlgn'])
						m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+': -</TD></TR>';
					else
						m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+': ' + formatUnixTime(rslt['lstlgn']) + '</TD></TR>';
				}
				m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+': ';
				if (rslt['knt'] != undefined)
					m+=rslt['knt']['cbt'];
				else
					m+=''+culang.mainNone+'';
				m+='</TD></TR>';

				if (rslt['pop'] != undefined)
					m+='<TR><TD>'+uW.g_js_strings.commonstr.population+': ' + addCommas(rslt['pop']) + '</TD></TR>';
				if (rslt['hap'] != undefined)
					m+='<TR><TD>'+uW.g_js_strings.commonstr.happiness+': ' + addCommas(rslt['hap']) + '</TD></TR></TABLE>';

				if (rslt['blds'] != undefined) {
					m+='<b><a id=KsRptBatClick>'+uW.g_js_strings.commonstr.buildings+'</a></b><br><TABLE class=pdxTab id=KsRptBat style="display:none">';
					for (var i=0; i<53; i++)
						if (rslt['blds']['b'+i] != undefined)
							m+=handleblds(i);
					m+='</TABLE>';
				}
				if (rslt['tch'] != undefined) {
					m+='<b><a id=KsRptRechercheClick>'+uW.g_js_strings.commonstr.technology+'</a></b><br><TABLE class=pdxTab id=KsRptRecherche style="display:none">';
					for (var tl=1; tl < 17; tl++)
						if (tl != 7)
							m+='</TD></TR><TR><TD>'+researchLevels[tl].Name+'</TD><TD align=right>' + rslt['tch']['t'+tl] + '</TD></TR>';
					m+='</TABLE>';
				}
			}
			//m+='</TD></TR></TABLE><br><input type=button value="'+culang.reportExportToCombat+'" id=KsExportCombat>';
			m+='</TD></TR></TABLE>';
		}

		if (rslt['fght'] != undefined){
			m+='<TABLE class=pdxTab width=100%><TR><TD width=50% align=left valign=top>';
			m+='<TABLE class=pdxTab width=100%>';
			m+='<TR><TD colspan=4><B>'+culang.mainAttacker+'</B> ('+rpt.side1Name+')';
			if (rslt['winner']==1)
				m+='<FONT color="#CC0000"><B> '+uW.g_js_strings.commonstr.winner+'</B></FONT>';
			m+='</TD></TR>';
			if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
				m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+': ' + rslt['s1KCombatLv'] + '</TD></TR>';
			if (rslt['s1atkBoost']!== undefined)
				if (100*rslt['s1atkBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.attackboosted+': ' + 100*rslt['s1atkBoost'] + '%</TD></TR>';
			if (rslt['s1defBoost']!== undefined)
				if (100*rslt['s1defBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.defenseboosted+': ' + 100*rslt['s1defBoost'] + '%</TD></TR>';
			if (rslt['s1lifeBoost']!== undefined)
				if (100*rslt['s1lifeBoost']>0)
					m+='<TR><TD colspan=4>Vie : ' + 100*rslt['s1lifeBoost'] + '%</TD></TR>';
			if (rslt['s1guardianDefBoost']!== undefined)
				if (100*rslt['s1guardianDefBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_defenseboosted+': ' + 100*rslt['s1guardianDefBoost'] + '%</TD></TR>';
			if (rslt['s1guardianAtkBoost']!== undefined)
				if ( 100*rslt['s1guardianAtkBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_attackboosted+': ' + 100*rslt['s1guardianAtkBoost'] + '%</TD></TR>';
			if (rslt['s1guardianMarchBoost']!== undefined)
				if (100*rslt['s1guardianMarchBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_marchboosted+': ' + 100*rslt['s1guardianMarchBoost'] + '%</TD></TR>';
			m+='<TR><TD colspan=4><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a> ' + rpt.side1CityName + '</TD></TR>';
			if (rslt['fght']["s1"] != undefined) {
				m+='<TR><TH></TH><TH align=left>'+uW.g_js_strings.commonstr.troops+'</TH><TH align=right>'+culang.reportFighted+'</TH><TH align=right>'+culang.reportSurvived+'</TH><TH align=right>'+culang.reportKilled+'</TH></TR>';
				for (var i=1;i<18;i++) {
					if (rslt['fght']["s1"]['u'+i] != undefined) {
						if (rslt['fght']["s1"]['u'+i][0] > rslt['fght']["s1"]['u'+i][1]) {
							perte_atk= perte_atk +(rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1])*puipui[i-1];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s1"]['u'+i][1])+'</FONT></td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1])+'</FONT></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][1])+'</td></tr>';
						}
					}
				}

				m+='<TR><TD colspan=4> </TD></TR>';
				m+='<TR><TD colspan=4> </TD></TR>';
				m+='<TR><TD colspan=4><b>Unit Stats:</b></TD></TR>';
				for (var i=1;i<18;i++) {
					if (rslt['fght']["s1"]['u'+i]) {
						m+='<TR><TD>' + unitImg[i] + '<font size="1"><b>HP: </b>'+addCommas(rslt['bonus']['mod']['s1']['u'+i]['hp'][1])+'<b>     Atk: </b>'+addCommas(rslt['bonus']['mod']['s1']['u'+i]['atk'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Def: </b>'+addCommas(rslt['bonus']['mod']['s1']['u'+i]['def'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Spd: </b>'+addCommas(rslt['bonus']['mod']['s1']['u'+i]['spd'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Rng: </b>'+addCommas(rslt['bonus']['mod']['s1']['u'+i]['rng'][1])+'</font></td></tr>';
					}
				}
			}
			m+='</TABLE><br>';
			// Bonus
			if (rslt['s1ThroneRoomBoosts']) {
				m+='<b><a id=KsRptS1ThroneClick>'+culang.reportShowThroneStuff+'</a></b><br><TABLE class=pdxTab id=KsRptS1Throne style="display:none">';
				for (var i in rslt['s1ThroneRoomBoosts']) {

					m+='<TR><TD><B>'+uW.cm.thronestats.effects[i][1]+'</B></td><td align=right>'+ rslt['s1ThroneRoomBoosts'][i] +' %</td></tr>';

				}
				m+='</TABLE>';
			}else{
				m+='<b>'+culang.reportNoThroneStuff+'</b>';
			}

			m+='</TD><TD width=50% align=left valign=top>';
			m+='<TABLE class=pdxTab width=100%>';
			m+='<TR><TD colspan=4><B>'+culang.mainDefender+'</B> ('+rpt.side0Name+')';
			if (rslt['winner']==0)
				m+='<FONT color="#CC0000"><B> '+uW.g_js_strings.commonstr.winner+'</B></FONT>';
			m+='</TD></TR>';
			if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
				m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+': ' + rslt['s0KCombatLv'] + '</TD></TR>';
			if (rslt['s0atkBoost'] !== undefined)
				if (100*rslt['s0atkBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.attackboosted+': ' + 100*rslt['s0atkBoost'] + '%</TD></TR>';
			if (rslt['s0defBoost'] !== undefined)
				if (rslt['s0defBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.defenseboosted+': ' + 100*rslt['s0defBoost'] + '%</TD></TR>';
			if (rslt['s0lifeBoost']!== undefined)
				if (100*rslt['s0lifeBoost']>0)
					m+='<TR><TD colspan=4>Vie : ' + 100*rslt['s0lifeBoost'] + '%</TD></TR>';
			if (rslt['s0guardianDefBoost']!== undefined)
				if (100*rslt['s0guardianDefBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_defenseboosted+': ' + 100*rslt['s0guardianDefBoost'] + '%</TD></TR>';
			if (rslt['s0guardianAtkBoost']!== undefined)
				if (100*rslt['s0guardianAtkBoost']>0)
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_attackboosted+': ' + 100*rslt['s0guardianAtkBoost'] + '%</TD></TR>';
			if (rslt['s0guardianMarchBoost']!== undefined)
				if (100*rslt['s0guardianMarchBoost'])
					m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_marchboosted+': ' + 100*rslt['s0guardianMarchBoost'] + '%</TD></TR>';
			if (rslt['rnds']!==undefined)
				m+='<TR><TD colspan=4>'+culang.mainRound+': ' + rslt['rnds'] + '</TD></TR>';
			if (rslt['fght']["s0"] != undefined) {
				m+='<TR><TH></TH><TH align=left>'+uW.g_js_strings.commonstr.troops+'</TH><TH align=right>'+culang.reportFighted+'</TH><TH align=right>'+culang.reportSurvived+'</TH></TR>';
				for (var i=1;i<18;i++) {
					if (rslt['fght']["s0"]['u'+i] != undefined) {
						if (rslt['fght']["s0"]['u'+i][0] > rslt['fght']["s0"]['u'+i][1]) {
							perte_def= perte_def +(rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1])*puipui[i-1];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['u'+i][1])+'</FONT></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][1])+'</td></tr>';
						}
					}
				}
				// Dark Forest
				for (var i=101;i<111;i++) {
					if (rslt['fght']["s0"]['m'+i] != undefined) {
						if (rslt['fght']["s0"]['m'+i][0] > rslt['fght']["s0"]['m'+i][1]) {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['m'+i][1])+'</FONT></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][1])+'</td></tr>';
						}
					}
				}
				//
				for (var i=53;i<=55;i++) {
					if (rslt['fght']["s0"]['f'+i] != undefined) {
						if (rslt['fght']["s0"]['f'+i][0] > rslt['fght']["s0"]['f'+i][1]) {
							perte_def= perte_def +(rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1])*puipui[i];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</font></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</td></tr>';
						}
					}
				}
				for (var i=60;i<=63;i++) {
					if (rslt['fght']["s0"]['f'+i] != undefined) {
						if (rslt['fght']["s0"]['f'+i][0] > rslt['fght']["s0"]['f'+i][1]) {
							perte_def= perte_def +(rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1])*puipui[i];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</font></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</td></tr>';
						}
					}
				}
				m+='<TR><TD colspan=4> </TD></TR>';
				m+='<TR><TD colspan=4> </TD></TR>';
				m+='<TR><TD colspan=4><b>Unit Stats:</b></TD></TR>';
				for (var i=1;i<18;i++) {
					if (rslt['fght']["s0"]['u'+i]) {
						m+='<TR><TD>' + unitImg[i] + '<font size="1"><b>HP: </b>'+addCommas(rslt['bonus']['mod']['s0']['u'+i]['hp'][1])+'<b>     Atk: </b>'+addCommas(rslt['bonus']['mod']['s0']['u'+i]['atk'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Def: </b>'+addCommas(rslt['bonus']['mod']['s0']['u'+i]['def'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Spd: </b>'+addCommas(rslt['bonus']['mod']['s0']['u'+i]['spd'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Rng: </b>'+addCommas(rslt['bonus']['mod']['s0']['u'+i]['rng'][1])+'</font></td></tr>';
					}
				}
				for (var i=53;i<=55;i++) {
					if (rslt['fght']["s0"]['f'+i]) {
						m+='<TR><TD>' + unitImg[i] + '<font size="1"><b>HP: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['hp'][1])+'<b>     Atk: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['atk'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Def: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['def'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Spd: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['spd'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Rng: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['rng'][1])+'</font></td></tr>';
					}
				}
				for (var i=60;i<=63;i++) {
					if (rslt['fght']["s0"]['f'+i]) {
						m+='<TR><TD>' + unitImg[i] + '<font size="1"><b>HP: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['hp'][1])+'<b>     Atk: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['atk'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Def: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['def'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Spd: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['spd'][1])+'</font></td>';
						m+='<TD align=left><font size="1"><b>Rng: </b>'+addCommas(rslt['bonus']['mod']['s0']['f'+i]['rng'][1])+'</font></td></tr>';
					}
				}
			} else
				m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.notroopsdef+'</TD></TR>';
			m+='</TABLE><br>';
			// Bonus divers ^^^
			if (rslt['s0ThroneRoomBoosts']) {
				m+='<b><a id=KsRptS0ThroneClick>'+culang.reportShowThroneStuff+'</a></b><br><TABLE class=pdxTab id=KsRptS0Throne style="display:none">';
				for (var i in rslt['s0ThroneRoomBoosts']) {

					m+='<TR><TD><B>'+uW.cm.thronestats.effects[i][1]+'</B></td><td align=right>'+ rslt['s0ThroneRoomBoosts'][i] +' %</td></tr>';

				}

				m+='</TABLE>';

			}else{
				m+='<b>'+culang.reportNoThroneStuff+'</b>'
			}

			m+='</TD></TR>';
			delta_perte = perte_atk - perte_def;
			delta_pos = 1;
			ordre_grandeur = 1; //par defaut: perte en k
			delta_perte = delta_perte/1000;
			if (delta_perte<0){
				delta_pos = -1; //plus de perte pour def
				delta_perte = Math.abs(delta_perte);
			}
			if (delta_perte>1000) { //perte en Mega
				ordre_grandeur = 2;
				delta_perte = entier_1dec(delta_perte/1000);
			}
			if (delta_perte<1) { 
				ordre_grandeur = 0;
				delta_perte = entier_1dec(delta_perte*1000);
			}
			if (ordre_grandeur == 1) { //perte en kilo => garde 1chiffre apres virgule
				delta_perte = entier_1dec(delta_perte);
			}
			// transforme les pertes en kilo (avec 1 chiffre derriere virgule)
			perte_atk = entier_1dec(perte_atk/1000);
			perte_def = entier_1dec(perte_def/1000);

			m+='<TR><TD colspan=4>&nbsp;</TD></TR>';
			// affichage 
			if ((delta_pos == 1) && (delta_perte != 0)) {
				m+='<TR><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side1Name+') : </FONT><FONT color="#CC0000"> '+(perte_atk)+'k</FONT></TD><TD><FONT color="#00"><b>'+culang.reportMightLoose+'</b> ('+rpt.side0Name+') : '+perte_def+'k </FONT></TD></TR>';
				if (ordre_grandeur==2) {
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'M</FONT></TD><TD></TD></TR></table>';
				} else if (ordre_grandeur==1){
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'k </FONT></TD><TD></TD></TR></table>';
				} else if(ordre_grandeur==0){
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'</FONT></TD><TD></TD></TR></table>';
				}
			}
			if ((delta_pos == -1) && (delta_perte != 0)) {
				m+='<TR><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side1Name+') : '+perte_atk+'k</FONT></TD><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side0Name+') : </FONT><FONT color="#CC0000"> '+perte_def+'k </FONT></TD></TR>';
				if (ordre_grandeur==2) {
					m+='<TR><TD></TD><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'M</FONT></TD></TR></table>';
				} else if (ordre_grandeur==1){
					m+='<TR><TD></TD><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'k</FONT></TD></TR></table>';
				} else if (ordre_grandeur==0){
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'</FONT></TD><TD></TD></TR></table>';
				}
			}
			if (delta_perte == 0 && (perte_def>0 || perte_atk>0)) {
				m+='<TR><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side1Name+'): '+perte_atk+'k</FONT></TD><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side0Name+'): '+perte_def+'k </FONT></TD></TR></TABLE>';
			}
		}

		m+='</DIV>';
		t.popReport.getMainDiv().innerHTML = m;
		t.popReport.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.mainReport+'</DIV>';
		t.popReport.show(true);
		t.popReport.autoHeight (true);
		if (ById('KsRptS0ThroneClick')) {
			ById('KsRptS0ThroneClick').addEventListener('click', function () {
				if (ById('KsRptS0Throne').style.display=="none") {ById('KsRptS0Throne').style.display="block";} else {ById('KsRptS0Throne').style.display="none";}
			},false);
		}
		if (ById('KsRptS1ThroneClick')) {
			ById('KsRptS1ThroneClick').addEventListener('click', function () {
				if (ById('KsRptS1Throne').style.display=="none") {ById('KsRptS1Throne').style.display="block";} else {ById('KsRptS1Throne').style.display="none";}
			},false);
		}
		if (ById('KsRptBatClick')) {
			ById('KsRptBatClick').addEventListener('click', function () {
				if (ById('KsRptBat').style.display=="none") {ById('KsRptBat').style.display="block";} else {ById('KsRptBat').style.display="none";}
			},false);
		}
		if (ById('KsRptRechercheClick')) {
			ById('KsRptRechercheClick').addEventListener('click', function () {
				if (ById('KsRptRecherche').style.display=="none") {ById('KsRptRecherche').style.display="block";} else {ById('KsRptRecherche').style.display="none";}
			},false);
		}
		if (ById('KsExportCombat')) {
			ById('KsExportCombat').addEventListener('click', function () {
				if (rslt['unts'] != undefined) {
					var A=0;
					for(var troops in uW.unitcost){
						A++;
						if (ById('pbcombatd_'+troops)) {
							if  (rslt['unts']['u'+A] != undefined)
								ById('pbcombatd_'+troops).value=rslt['unts']['u'+A];
							else
								ById('pbcombatd_'+troops).value=0;
						}
					}
				}
				// on remplit la technologie de la defenses
				if (rslt['tch'] != undefined) {
					CombatOptions.research[0]['tch8']=rslt['tch']['t8'];
					CombatOptions.research[0]['tch9']=rslt['tch']['t9'];
					CombatOptions.research[0]['tch13']=rslt['tch']['t13'];
					CombatOptions.research[0]['tch15']=rslt['tch']['t15'];
				}
				// chevalier
				if (rslt['knt'] != undefined) CombatOptions.knt[0] = rslt['knt']['cbt'];

				Tabs2.Combat.e_calculate();

				saveCombatOptions();

			}, false);


		}


	},

};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Marches.js">
//	
//	   KOC POWER - TABS MARCHES										        
//	


Tabs.Marches = {
	tabOrder: TabOptions.toMarches,
	tabLabel: culang.tabLabelMarch,
	cont:null,
	displayTimer:null,
	curTabBut : null,
	curTabName : null,
	state : null,

	hide : function (){
		var t = Tabs.Marches;
		clearTimeout (t.displayTimer);
	},

	show : function (){
		var t = Tabs.Marches;
		clearTimeout (t.displayTimer);
		if (t.curTabName == 'Z')
			t.showReinforcementsOut();
		else if (t.curTabName == 'R')
			t.showReinforcements();
		else if (t.curTabName == 'M')
			t.showMarches(9);
		else
			t.showAttacks();
	},
	init : function (div){
		var t = Tabs.Marches;
		t.cont = div;
		uW.pr58Recall = t.ajaxRecall;
		uW.Ksraid_delete = t.ajaxDeleteRaid;
		uW.r8x6Home = t.butSendHome;
		uW.pr57Recall = t.butRecall2;

		var atkclass='';
		if(Seed && Seed.queue_atkinc) {
			for(k in Seed.queue_atkinc){
				m = Seed.queue_atkinc[k];
				if (m.marchType == 4){
					atkclass = 'style="background-color:#FF9999;"';
				}
			}
		}

		t.cont.innerHTML = '<TABLE class=pdxTab align=center><TR><TD><INPUT class=ksMSubtab ID=BoptmrchSubM type=submit value="'+ culang.mainMarches +'"></td>\
          <TD><INPUT class=ksMSubtab ID=BoptmrchSubA type=submit '+atkclass+' value="' + culang.marchIncommingButtonLabel + '"></td>\
          <TD><INPUT class=ksMSubtab ID=BoptmrchSubR type=submit value="'+culang.mainEmbassy+'"></td>\
          <TD><INPUT class=ksMSubtab ID=BoptmrchSubZ type=submit value="'+culang.mainReinforcement+'"></td><td><input type=button value="?" id=boaidemarches class=buttonHelp></td></tr></table>\
      <DIV id="BoptMarchOutput" style="margin-top:5px;max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
		t.marchDiv = ById('BoptMarchOutput');
		ById('BoptmrchSubA').addEventListener('click', e_butSubtab, false);
		ById('BoptmrchSubR').addEventListener('click', e_butSubtab, false);
		ById('BoptmrchSubM').addEventListener('click', e_butSubtab, false);
		ById('BoptmrchSubZ').addEventListener('click', e_butSubtab, false);
		ById('boaidemarches').addEventListener('click', function(){
			window.open(homePage+" ");
		} , false);
		if (atkclass!='') {
			changeSubtab (ById('BoptmrchSubA'));
		}else {
			changeSubtab (ById('BoptmrchSubM'));
		}

		function e_butSubtab (evt){
			changeSubtab (evt.target);
		}

		function changeSubtab (but){
			if (but == t.curTabBut)
				return;
			if (t.curTabBut){
				t.curTabBut.className='ksMSubtab';
				t.curTabBut.disabled=false;
			}
			t.curTabBut = but;
			but.className='ksMSubtab ksMSubtabSel';
			but.disabled=true;
			t.curTabName = but.id.substr(11);
			if (Options.currentTab=="Marches") t.show2();
		}

	},
	show2 : function (){
		var t = Tabs.Marches;
		t.state = null;
		clearTimeout (t.displayTimer);
		if (t.curTabName == 'Z')
			t.showReinforcementsOut();
		else if (t.curTabName == 'R')
			t.showReinforcements();
		else if (t.curTabName == 'M')
			t.showMarches(9);
		else
			t.showAttacks();
	},

	/***   ATTACKS SUBTAB  ***/
	showAttacks : function (){
		var t = Tabs.Marches;
		clearTimeout (t.displayTimer);
		var now = unixTime();
		var target, atkType, who, atkclass;
		var ss = '<div class=pdxStat>'+culang.marchIncommingHead+' - <input type=button value="?" id=boaidemarches2 class=buttonHelp></div>';
		var s = '';
		s += '<STYLE> .eclkk{background:#ffff55;} .attackkk{background:#ff5555;} .attackkA{background:#ff9955;}</style>';
		s += '<TABLE border=0 cellspacing=0 cellpadding=2 width=100% class=pdxTab>';
		s += '<tr><td width=55><b><u>'+culang.mainArrival+'</u></b></td><td width=60><b><u>'+culang.mainDefense+'</u></b> </td><td width=140 colspan=2><b><u>'+culang.mainCastle+'</u></b></td><td width=150 colspan=2><b><u>'+culang.mainAttacker+'</u></b></td><td width=35><b><u>'+culang.mainDistance+ '</u></b></td><td width=25><b><u>'+culang.mainKnights+'</u></b></td><td><b><u>'+culang.mainTroops+'</u></b></td></tr>';
		var at=0;
		if(Seed && Seed.queue_atkinc) {
			var sortem = [];
			for (var k in Seed.queue_atkinc)
				sortem.push (Seed.queue_atkinc[k]);

			sortem.sort (function (a,b){
				var x; if ((x = a.arrivalTime-b.arrivalTime)!=0)
					return x;
				return b.arrivalTime-a.arrivalTime;
			});

			for (i=0; i<sortem.length; i++){
				var m = sortem[i];

				if (m.marchType == 3){
					atkType = culang.mainScouting;
					atkclass = 'eclkk';
				} else if (m.marchType == 4){
					atkType = uW.g_js_strings.commonstr.atk;
					atkclass = 'attackkk';
					var nbtroupe=0;
					for (k in m.unts){
						nbtroupe += parseInt(m.unts[k]);
					}
					if (nbtroupe==1) {
						atkclass = 'attackkA';
					}

				} else {
					atkType ="?";
					atkclass = '';
				}
				if (atkclass !='') {
					at++;
					s += '<tr align=left class="'+atkclass+'">';
					var arrivedans = uW.timestr(parseInt(m.arrivalTime - unixTime()));
					s += '<td class="'+atkclass+'">' + arrivedans +'</td>';
					var couelur="";
					var city = Cities.byID[m.toCityId];
					if (city.tileId == m.toTileId) {
						target = '<a onclick="citysel_click(document.getElementById(\'citysel_'+ (city.idx+1)+'\'));">'+ city.name.substring(0,10) +'</a>';
						cityID = 'city'+ m.toCityId;
						Gate = parseInt(Seed.citystats[cityID].gate);
						if(Gate == 0) {
							bouttt = '<input type=button value="'+culang.mainHDef+' = '+culang.buttonOFF+'" id="but_'+m.toCityId+'" style="background-color:#00AA00;padding:2px;border:1px solid yellow;">';
						}	   else {
							bouttt = '<input type=button value="'+culang.mainHDef+' = '+culang.buttonON+'" id="but_'+m.toCityId+'" style="background-color:red;">';
						}
						coordos = '<a class="coordinateLink" onclick="clickKoords(event)" href="javascript:void(0)">('+ city.x + ',' + city.y +')</a>';
					} else {
						target = 'WILD';
						bouttt='';
						for (k in Seed.wilderness['city'+m.toCityId]){
							if (Seed.wilderness['city'+m.toCityId][k].tileId == m.toTileId){
								coordos = '<a class="coordinateLink" onclick="clickKoords(event)" href="javascript:void(0)">('+Seed.wilderness['city'+m.toCityId][k].xCoord + ',' + Seed.wilderness['city'+m.toCityId][k].yCoord+')</a>';
								break;
							}
						}
					}
					s += '<td class="'+atkclass+'" align=center>'+bouttt+'</td><td class="'+atkclass+'" align=center><b>' + target + '<td class="'+atkclass+'" align=center>'+coordos+'</b></td>';

					if (Seed.players['u'+m.pid]) {
						who = '<span>'+Seed.players['u'+m.pid].n +'<br>'+addCommas(Seed.players['u'+m.pid].m)+'</span>';

					} else if (m.players && m.players['u'+m.pid]) {
						who = m.players['u'+m.pid].n;
					} else{
						who = ''+culang.mainUnknown+'';

					}
					if (m.fromXCoord) {
						who += '</td><td class="'+atkclass+'"><a class="coordinateLink" onclick="clickKoords(event)" href="javascript:void(0)">(' + m.fromXCoord +','+ m.fromYCoord+')</a>';
					} else {
						who += '</td><td class="'+atkclass+'">???</a></td>';
					}
					s += '<td class="'+atkclass+'">' + who + '</td>';
					if (m.fromXCoord) {
						s +='<td class="'+atkclass+'">'+ distance(city.x,city.y,m.fromXCoord,m.fromYCoord) +'</td>';
					} else {
						s +='<td class="'+atkclass+'">&nbsp;</td>';
					}
					var troupe = "";
					for (k in m.unts){
						var uid = parseInt(k.substr (1));
						troupe += m.unts[k] +' '+ uW.unitcost['unt'+uid][0] +'<br>';
					}
					var knh='&nbsp;';
					if (m.knt) {
						for (k in m.knt){
							knh=parseInt(m.knt[k]);
						}
					}
					s += '<td class="'+atkclass+'">'+knh+'</td>';
					s += '<td class="'+atkclass+'">' + troupe +'</td>';

					s += '</tr>';
				}
			}
			s+='</table>';
			if (at==0) {
				s ="<tr><colspan=4><br><center><i><b>"+culang.marchIncommingHeadNoAttacks+"</b></i></center></td></tr>";
			}
		}
		t.marchDiv.innerHTML = ss + "" + s;
		ById('boaidemarches2').addEventListener('click', function(){
			window.open(homePage+" ");
		} , false);
		for (var cityId in Cities.byID){
			var but = document.getElementById ('but_'+ cityId);
			if (but) addListener (but, cityId);
		}
		function addListener (but, i){      	 but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);       }

		t.displayTimer = setTimeout (t.showAttacks, 900);
	},
	defMode:{},
	butToggleDefMode : function (cityId){
		var t = Tabs.Marches;
		var mode = 1;
		if (Seed.citystats["city" + cityId].gate != 0)
			mode = 0;
		t.ajaxSetDefMode (cityId, mode, function (newMode){

		});
	},
	ajaxSetDefMode : function (cityId, state, notify){
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid = cityId;
		params.state = state;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/gate.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					Seed.citystats["city" + cityId].gate = state;
					notify (state);
				}
			},
			onFailure: function () {
			}
		})
	},

	/***   MARCHES SUBTAB  ***/
	showMarches : function (numville){

		var t = Tabs.Marches;
		var rownum = 0;
		var now = unixTime();
		var names = [''+culang.shrsupply+'', ''+culang.shrmilitiaman+'', ''+culang.scout+'', ''+culang.shrpikeman+'', ''+culang.shrswordsman+'', ''+culang.shrtarcher+'', ''+culang.shrcavalry+'', ''+culang.shrheavycavalry+'', ''+culang.shrsupplywagon+'', ''+culang.shrballista+'', ''+culang.shrbatteringram+'', ''+culang.shrcatapult+'', ''+culang.shrbloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'', ''+culang.shrflarcher+'', 'Hsr']; 
		clearTimeout (t.displayTimer);
		if (t.state == null){
			var s = '<div class=pdxStat>'+culang.marchHead+' <input type=button value="?" id=boaidemarches1 class=buttonHelp></div>';
			s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;}</style> <input style="font-size:12px" type=button id="9_KsVilleBouton" value="0">';
			for (var c=0; c<Cities.numCities; c++){
				s += '<input style="font-size:12px" type=button id="'+ c +'_KsVilleBouton" value="' + (parseInt(c)+1) + ': '+ Cities.cities[c].name.substring(0,10) +'">';
			}
			s += '<br><input id=KsVoirRaid type=checkbox '+ (!Options.voirRaid?'':' CHECKED ') +'> <b>'+culang.marchHideRaid+'</b> <div id="showMarchDiv"></div>';
			t.marchDiv.innerHTML = s;
			ById('boaidemarches1').addEventListener('click', function(){
				window.open(homePage+" ");
			} , false);
			ById('KsVoirRaid').addEventListener('click', function() {

				Options.voirRaid = ById('KsVoirRaid').checked;
				saveOptions();

			}, false);

			ById("9_KsVilleBouton").addEventListener('click', function(){
				var t = Tabs.Marches;
				clearTimeout (t.displayTimer);
				t.showMarches(this.id.substring(0,1));

			}, false);

			for (var c=0; c<Cities.numCities; c++){
				ById(c + "_KsVilleBouton").addEventListener('click', function(){
					var t = Tabs.Marches;
					clearTimeout (t.displayTimer);
					t.showMarches(this.id.substring(0,1));
				}, false);
			}
			t.state = 1;
		}
		s = '<TABLE cellspacing=0 cellpadding=2 width=100% class=pdxTab>';
		tot = [];
		for (i=0; i<18; i++)  tot[i] = 0;
		var c = numville;
		if (numville==9) {
			for (var c=0; c<Cities.numCities; c++){
				var que = Seed.queue_atkp['city'+ Cities.cities[c].id];

				if (matTypeof(que)=='object') {
					var a=0;
					for (k in que) {
						march = que[k];
						if ((march.marchType!=2 && !Options.voirRaid) || (march.marchType!=9 && march.marchType!=2 && Options.voirRaid) ) {
							a++;
							if (a==1) {
								var cityID = 'city'+ Cities.cities[c].id;
								var rinfo = getRallypointInfo(Cities.cities[c].id);
								var niveauPointRall = rinfo.maxMarches;
								var slots = rinfo.usedSlots;
								s+= '<TR class="city"><TD class="city">'+culang.mainSRallyPoint+': '+slots+' / '+niveauPointRall+'</td><TD class="city" colspan=19 align=center><font size=3><B><i><u>'+culang.mainCastle+' ' + (parseInt(c)+1) + ' - '+ Cities.cities[c].name +'</b></td></tr>';
							}
							var mid = k.substr(1);
							knight = '';
							if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
								for (i in Seed.knights['city'+ Cities.cities[c].id]) {
									if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +'';
								}
							} else knight = '';
							var playerId = march.toPlayerId;
							if (playerId==undefined) playerId=0;
							var cityId = march.toCityId;
							var tileType = parseInt(march.toTileType);
							var tileLevel = march.toTileLevel;
							var who = ''+culang.mainUnknown+'';
							if (Seed.players['u' + playerId]) {
								who = Seed.players['u' + playerId].n;
							}
							if (march.marchType==1) {
								var player = "<span>"+culang.mainCity+" "+ tileLevel +"</span>";
							}else {
								var player = "<span title='"+culang.reportBarbLevelNote+"'>"+culang.kocShortBarbarian+" "+ tileLevel +"</span>";
							}
							if (march.marchType==10 || march.marchType==11) {
								var player = "<span>"+culang.shortDarkForest+": "+ tileLevel +"</span>";
							}
							var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills, uW.g_js_strings.commonstr.mountain, uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, uW.g_js_strings.commonstr.darkForest];
							var numtile=parseInt(tileType/10) + 1;
							if (tileType==10) numtile=1;
							if (tileType==11) numtile=2;
							if (tileType <= 50) {
								player = tileNames[numtile] +" " + tileLevel;
							}
							if (tileType == 51 && playerId == 0 && march.toTileLevel==7) {
								player = uW.g_js_strings.commonstr.city+" " + tileLevel;
							}
							if (tileType == 51 && playerId == 0 && march.toTileLevel==9) {
								player = ""+culang.kocShortBarbarian+" " + tileLevel;
							}
							if (tileType == 54 && playerId == 0) {
								player = ""+culang.shortDarkForest+": " + tileLevel;
							}
							var nomville="";
							if (playerId > 0 && tileType == 51) {
								if (march.marchType==1) {
									for(i=0; i<Cities.numCities; i++) {
										if (cityId==Cities.cities[i].id) {
											nomville=Cities.cities[i].name
											break;
										}
									}

									player = ''+culang.mainCastle+' '+ nomville;
								} else {
									player = ''+culang.reportCityLevel+' ' + tileLevel;
								}
							}
							var typeattack="?";
							if (march.marchType==3) typeattack=culang.mainScouting;
							if (march.marchType==4) typeattack=culang.mainAttack;
							if (march.marchType==10) typeattack=culang.mainAttack;
							if (march.marchType==11) typeattack=culang.mainScouting;
							if (march.marchType==1) typeattack=culang.mainTransport;
							if (march.marchType==5) typeattack=culang.mainReassign;
							if (march.marchType==9) typeattack=culang.mainRaidAttack;
							var now = new Date();
							var statusm = march.marchStatus;
							var Marchstatut="<span title='"+culang.mainType+": "+march.marchType+" "+culang.mainStatus+": "+statusm+"'>?</span> ";
							var arrivedans="0s";
							var arrivedanssec=0;
							if (statusm==1) {
								Marchstatut="";
								if (march.marchType==3 || march.marchType==11)
									Marchstatut+='<img src="'+IMGmarchScouting+'" align=absmiddle>';
								if (march.marchType==4 || march.marchType==10)
									Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
								if (march.marchType==9)
									Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
								if (march.marchType==1)
									Marchstatut+='<img src="'+IMGmarchTransporting+'" align=absmiddle>';
								if (march.marchType==5)
									Marchstatut+='<img src="'+IMGmarchReinforce+'" align=absmiddle>';
								Marchstatut+="&nbsp;"+uW.g_js_strings.commonstr.marching;
								arrivedans = uW.timestr(parseInt(march.destinationUnixTime - unixTime()));
								arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
							}
							if (statusm==8) {
								Marchstatut = '<img src="'+IMGmarchReturning+'" align=absmiddle>&nbsp;'+culang.mainReturn;
								arrivedans = uW.timestr(march.returnUnixTime - unixTime());
								arrivedanssec = parseInt(march.returnUnixTime - unixTime());
							}
							if (statusm==2) {
								Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+culang.mainCamped;
							}
							if (statusm==5) {
								Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
							}
							if (statusm==4) {
								Marchstatut='<img src="'+IMGmarchRaidReset+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.unloadingloot;
							}
							if (statusm==3 || statusm==10 ) {
								Marchstatut='<img src="'+IMGmarchRaidStoppedDesat+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.raidstopped;
							}

							s += '<TR align=left><td align=left width=10%>';
							if (march.marchType!=9 && statusm==1 && arrivedanssec>60) s +='<A onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')" title="'+culang.marchRecallMarchNote+'"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
							if (march.marchType!=9 && statusm==2) s +='<A onclick="attack_recall('+ mid+', 1, '+Cities.cities[c].id+');" title="'+culang.marchRecallAttackNote+'"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
							if (march.marchType==9 && statusm==10 && arrivedanssec<=0) s +='<A onclick="Ksraid_delete('+ mid+','+Cities.cities[c].id+');return false;" title="'+culang.marchDeleteRaidNote+'"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></a>';

							s +='</td><td align=left width=10%>'+typeattack+'</td><td>'+arrivedans+'</td><td align=left width=15%>' + Marchstatut +'</td>\
                <TD align=left width=15%>' + player + '</td><td><a class="coordinateLink" onclick="clickKoords(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a></td><td>' + knight +' </td><td colspan=12>'
							for (i=1; i<18; i++) {
								if (statusm==8) {
									if (parseInt (march['unit'+ i +'Return']) > 0) {
										//s += uW.unitcost['unt'+i][0].substr(0,6)+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
										s += names[i-1].substr(0,6)+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
										tot[i] += parseInt (march['unit'+ i +'Return']);
									}

								} else {
									if (parseInt (march['unit'+ i +'Count']) > 0) {
										//s += uW.unitcost['unt'+ i][0].substr(0,6) +" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
										s += names[i-1].substr(0,6) +" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
										tot[i] += parseInt (march['unit'+ i +'Count']);
									}
								}
							}

							s += '</td><td style="font-size:11px">';
							if (march.marchType!=9) {
								s += '<a onclick="view_march('+ mid+');return false;"; title="'+culang.marchShowDetailsNote+'"><span><img  border=0 src="'+IMGshowButton+'"></span></a></td>';
							}else {
								s+='</td>';
							}
							s += '</tr>';
						}
					}
				}
			}
			s += '<TR><TD colspan=22><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100%><tr><td colspan=1></td>';
			for (var k=1;k<18;k++)
				s += '<TD width=6% align=center><img title="' + uW.unitcost['unt'+k][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+k+'_30.jpg></td>';
			s += '</tr>';
			s += '<TR align=center><TD class="tot" align=left width=10%><B>'+culang.mainHTotal+'</b></td>';
			for (i=1; i<18; i++)
				s+= '<TD class="tot">'+ addCommas(tot[i]) +'</td>';
			s += '<td></td></tr></table>';
			s += '<BR><BR><DIV style="font-size: 10px"></div>';

		} else {

			var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
			if (matTypeof(que)=='object') {
				var a=0;
				for (k in que){
					march = que[k];

					if ((march.marchType!=2 && !Options.voirRaid) || (march.marchType!=9 && march.marchType!=2 && Options.voirRaid) ) { 
						a++;
						if (a==1) {
							var cityID = 'city'+ Cities.cities[c].id;
							var rinfo = getRallypointInfo(Cities.cities[c].id);
							var niveauPointRall = rinfo.maxMarches;
							var slots = rinfo.usedSlots;
							s+= '<TR class="city"><TD class="city">'+culang.mainSRallyPoint+': '+slots+' / '+niveauPointRall+'</td><TD class="city" colspan=19 align=center><font size=3><B><i><u>'+uW.g_js_strings.commonstr.city+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
						}
						var mid = k.substr(1);
						knight = '';
						if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
							for (i in Seed.knights['city'+ Cities.cities[c].id]) {
								if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '&nbsp;('+culang.mainKnights+': ' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +')';
							}
						} else knight = '';
						var playerId = march.toPlayerId;
						if (playerId==undefined) playerId=0;
						var cityId = march.toCityId;
						var tileType = parseInt(march.toTileType);
						var tileLevel = march.toTileLevel;
						var who = ''+culang.mainUnknown+'';
						if (Seed.players['u' + playerId]) {
							who = Seed.players['u' + playerId].n;
						}
						if (march.marchType==1) { // si transport c'est forcement sur une ville lol
							var player = "<span>"+culang.marchCityLevel+" "+ tileLevel +"</span>";
						}else {
							var player = "<span title='"+culang.reportBarbLevelNote+"'>"+culang.reportBarbLevel+" "+ tileLevel +"</span>";
						}
						if (march.marchType==10 || march.marchType==11) {
							var player = "<span>"+culang.shortDarkForest+": "+culang.shortLevel+" "+ tileLevel +"</span>";
						}
						var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills,   uW.g_js_strings.commonstr.mountain,  uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, uW.g_js_strings.commonstr.darkForest];

						var numtile=parseInt(tileType/10) + 1;
						if (tileType==10) numtile=1;
						if (tileType==11) numtile=2;
						if (tileType <= 50) { // TS
							player = tileNames[numtile] +" "+culang.shortLevel+" " + tileLevel;
						}
						if (tileType == 51 && playerId == 0 && march.toTileLevel==7) { // Ville
							player = ""+culang.marchCityLevel+" " + tileLevel;
						}
						if (tileType == 51 && playerId == 0 && march.toTileLevel==9) { // Barbares
							player = ""+culang.reportBarbLevel+" " + tileLevel;
						}
						if (tileType == 54 && playerId == 0) { // Barbares
							player = ""+culang.shortDarkForest+": "+culang.shortLevel+" " + tileLevel;
						}
						var nomville="";
						if (playerId > 0 && tileType == 51) { // ville
							if (march.marchType==1) {
								for(i=0; i<Cities.numCities; i++) {
									if (cityId==Cities.cities[i].id) {
										nomville=Cities.cities[i].name
										break;
									}
								}
								player = ''+culang.mainCity+' '+ nomville;
							} else {
								player = ''+culang.reportCityLevel+' ' + tileLevel;
							}
						}
						var typeattack="?";



						if (march.marchType==3) typeattack=culang.mainScouting;
						if (march.marchType==4) typeattack=culang.mainAttack;
						if (march.marchType==10) typeattack=culang.mainAttack;
						if (march.marchType==11) typeattack=culang.mainScouting;
						if (march.marchType==1) typeattack=culang.mainTransport;
						if (march.marchType==5) typeattack=culang.mainReassign;
						if (march.marchType==9) typeattack=culang.mainRaidAttack;
						var now = new Date();
						var statusm = march.marchStatus;
						var Marchstatut="<span title='"+culang.mainType+": "+march.marchType+" "+culang.mainStatus+": "+statusm+"'>?</span> ";
						var arrivedans="0s";
						var arrivedanssec=0;
						if (statusm==1) {
							Marchstatut="";
							if (march.marchType==3 || march.marchType==11)
								Marchstatut+='<img src="'+IMGmarchScouting+'" align=absmiddle>';
							if (march.marchType==4 || march.marchType==10)
								Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
							if (march.marchType==9)
								Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
							if (march.marchType==1)
								Marchstatut+='<img src="'+IMGmarchTransporting+'" align=absmiddle>';
							if (march.marchType==5)
								Marchstatut+='<img src="'+IMGmarchReinforce+'" align=absmiddle>';
							Marchstatut+="&nbsp;"+uW.g_js_strings.commonstr.marching;
							arrivedans = uW.timestr(parseInt(march.destinationUnixTime - unixTime()));
							arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
						}
						if (statusm==8) {
							Marchstatut = '<img src="'+IMGmarchReturning+'" align=absmiddle>&nbsp;'+culang.mainReturn;
							arrivedans = uW.timestr(march.returnUnixTime - unixTime());
							arrivedanssec = parseInt(march.returnUnixTime - unixTime());
						}
						if (statusm==2) {
							Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+culang.mainCamped;
						}
						if (statusm==5) {
							Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
						}
						if (statusm==4) {
							Marchstatut='<img src="'+IMGmarchRaidReset+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.unloadingloot;
						}
						if (statusm==3 || statusm==10) {
							Marchstatut='<img src="'+IMGmarchRaidStoppedDesat+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.raidstopped;
						}

						s += '<TR align=left><td align=left width=10%>';
						if (march.marchType!=9 && statusm==1 && arrivedanssec>60) s +='<A onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
						if (march.marchType!=9 && statusm==2) s +='<A onclick="attack_recall('+ mid+', 1, '+Cities.cities[c].id+');"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
						if (march.marchType==9 && statusm==10 && arrivedanssec<=0) s +='<A onclick="Ksraid_delete('+ mid+','+Cities.cities[c].id+');return false;"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></a>';

						s +='</td><td align=left width=10%>'+typeattack+'</td><td>'+arrivedans+'</td><td align=left width=15%>' + Marchstatut +'</td>\
	                      <TD align=left width=15%>' + player + '</td><td><a class="coordinateLink" onclick="clickKoords(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a></td><td>' + knight +' </td><td colspan=12>'
						for (i=1; i<18; i++) {
							if (statusm==8) {
								if (parseInt (march['unit'+ i +'Return']) > 0) {
									s += names[i-1]+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
									tot[i] += parseInt (march['unit'+ i +'Return']);
								}

							} else {
								if (parseInt (march['unit'+ i +'Count']) > 0) {
									s += names[i-1]+" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
									tot[i] += parseInt (march['unit'+ i +'Count']);
								}
							}
						}

						s += '</td><td style="font-size:11px">';
						if (march.marchType!=9) {
							s += '<a  onclick="view_march('+ mid+');return false;"; title="'+culang.marchShowDetailsNote+'"><span><img border=0 src="'+IMGshowButton+'"></span></a></td>';
						}else {
							s+='</td>';
						}
						s += '</tr>';
					}// fin de MarchType
				} // fin k in que
				s += '<TR><TD colspan=20><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100% class=pdxTab ><tr><td colspan=1></td>';
				for (k=0; k<names.length; k++)  
				s += '<TD width=6% align=center><img title="' + uW.unitcost['unt'+(k+1)][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+(k+1)+'_30.jpg></td>';
				s += '</tr>';
				s += '<TR align=center><TD class="tot" align=left width=10%><B>'+culang.mainHTotal+'</b></td>';
				for (i=1; i<18; i++) s+= '<TD class="tot">'+ addCommas(tot[i]) +'</td>';
				s += '<td></td></tr></table>';
			} else {
				s= '<br><center><b><i>'+culang.marchNoMarches+'</i></b></center>';
			}
		} // Fin c=99
		ById('showMarchDiv').innerHTML = s;
		t.displayTimer = setTimeout (function() { t.showMarches(numville);   }, 1000);
	},
	ajaxDeleteRaid: function(marchId, cityId) {
		var villeencours=cityId;
		var march = Seed.queue_atkp["city" + villeencours]["m" + marchId];
		if (march == null){
			return;
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="deleteMarch";
		params.marchId = marchId;
		params.ctrl="BotManager";
		params.settings={cityId:villeencours};
		uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
			onSuccess:function(transport) {
				var m = eval("(" + transport.responseText + ")");
				if (m.ok){
					var j=marchId;
					var t=cityId;
					var n=Seed.units["city"+t];
					for(var o=0;o<18;++o){
						if (m["unit"+o+"Return"]) {
							var p=parseInt(m["unit"+o+"Return"]);
							if(!isNaN(p)&&(p>0)){
								n["unt"+o]=parseInt(n["unt"+o])+p;
							}
						}
					}
					uW.cityinfo_army();
					var s="city"+t;
					// recherche de mon chevalier
					var mymarch = uW.seed.queue_atkp["city" + t]["m" + j];
					var kngId= mymarch.knightId;
					delete Seed.queue_atkp[s]["m"+j];
					if(uW.Object.keys(Seed.queue_atkp[s]).length==0){
						Seed.queue_atkp[s]=[];
					}
					Seed.knights["city"+t]["knt"+kngId].knightStatus=1;
				} else {


				}
			}, onFailure: function () {

			},
		});

	},
	/***  REINFORCEMENTS SUBTAB  ***/
	showReinforcementsOut : function (){
		var rownum = 0;
		var names = [''+culang.shrsupply+'', ''+culang.shrmilitiaman+'', ''+culang.scout+'', ''+culang.shrpikeman+'', ''+culang.shrswordsman+'', ''+culang.shrtarcher+'', ''+culang.shrcavalry+'', ''+culang.shrheavycavalry+'', ''+culang.shrsupplywagon+'', ''+culang.shrballista+'', ''+culang.shrbatteringram+'', ''+culang.shrcatapult+'', ''+culang.shrbloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'', ''+culang.shrflarcher+'', 'Hsr']; 
		var t = Tabs.Marches;
		clearTimeout (t.displayTimer);
		var s = '<div class=pdxStat>'+culang.marchReinforcementHead+' - <input type=button value="?" id=boaidemarches4 class=buttonHelp></div>';
		s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;}</style>';
		s += '<TABLE cellspacing=0 cellpadding=2 width=100% class=pdxTab >';
		tot = [];
		for (i=0; i<18; i++)
			tot[i] = 0;

		for (var c=0; c<Cities.numCities; c++){
			var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
			if (matTypeof(que)=='array')
				continue;

			var a=0;
			for (k in que){
				march = que[k];
				if (march.marchType==2) {
					a++;
					if (a==1) {
						s+= '<TR class="city"><TD class="city" colspan=17 align=left><B>'+culang.mainCastle+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
					}
					var mid = k.substr(1);
					knight = '';
					if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
						for (i in Seed.knights['city'+ Cities.cities[c].id]) {
							if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +'';
						}
					} else knight = '';
					if (parseInt(march.knightCombat)>0) knight=' ('+ march.knightCombat +')';
					try {
						player = Seed.players['u'+march.toPlayerId].n; //Seed.players['u'+k].n;
					} catch (err){
						player = ''+culang.mainUnknown+'';
					}

					s += '<TR align=left><td align=left width=12%>';
					var statusm = march.marchStatus;
					var Marchstatut='';
					var arrivedans="0s";
					var arrivedanssec=0;
					if (statusm==1) {
						Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.commonstr.marching;
						arrivedans = uW.timestr(parseInt(march.destinationUnixTime - unixTime()));
						arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
					}
					if (statusm==2) {
						Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+culang.mainCamped;
					}
					if (statusm==8) {
						Marchstatut='<img src="'+IMGmarchReturning+'" align=absmiddle>&nbsp;'+culang.mainReturn;
						arrivedans = uW.timestr(parseInt(march.returnUnixTime - unixTime()));
						arrivedanssec = parseInt(march.returnUnixTime - unixTime());
					}
					if (statusm==5) {
						Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
					}
					if (statusm==1 && arrivedanssec>60){
						s +='<A onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')" title="'+culang.marchReinforcementRecallTroopsNowNote+'"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
					}
					if (statusm==2) {
						s +='<A onclick="pr57Recall('+ mid+')"  title="'+culang.marchReinforcementRecallTroopsNowNote+'"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
					} else {
						s += '&nbsp;';
					}

					s+='</td><td align=left width=15%>'+Marchstatut+'</td><td>'+arrivedans+'</td><TD align=left width=30%>' + player + ' <a class="coordinateLink" onclick="clickKoords(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a>&nbsp;' + knight +' </td><td colspan=12>'
					for (i=1; i<18; i++) {
						if (statusm==8) {
							if (parseInt (march['unit'+ i +'Return']) > 0) {
								s += " " + parseInt (march['unit'+ i +'Return']) + " "+names[i-1]+"<br>";
								tot[i] += parseInt (march['unit'+ i +'Return']);
							}

						} else {
							if (parseInt (march['unit'+ i +'Count']) > 0) {
								s += " " + parseInt (march['unit'+ i +'Count']) + " "+names[i-1]+"<br>";
								tot[i] += parseInt (march['unit'+ i +'Count']);
							}
						}
					}
					s += '</td></tr>';
				}// fin de MarchType
			}
		}

		s += '<TR><TD colspan=19><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 class=pdxTab width=100%><tr><td colspan=1></td>';
		for (k=0; k<names.length; k++)
				s += '<TD width=6% align=center><img title="' + uW.unitcost['unt'+(k+1)][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+(k+1)+'_30.jpg></td>';

		s += '</tr>';
		s += '<TR align=center><TD class="tot" align=left width=10%><B>'+culang.mainHTotal+'</b></td>';
		for (i=1; i<18; i++)
			s+= '<TD class="tot">'+ addCommas(tot[i]) +'</td>';
		s += '</tr></table>';
		t.marchDiv.innerHTML = s;
		ById('boaidemarches4').addEventListener('click', function(){
			window.open(homePage+" ");
		} , false);
		t.displayTimer = setTimeout (t.showReinforcementsOut, 5000);
		return;
	},

	showReinforcements : function (){
		var rownum = 0;
		var names = [''+culang.shrsupply+'', ''+culang.shrmilitiaman+'', ''+culang.scout+'', ''+culang.shrpikeman+'', ''+culang.shrswordsman+'', ''+culang.shrtarcher+'', ''+culang.shrcavalry+'', ''+culang.shrheavycavalry+'', ''+culang.shrsupplywagon+'', ''+culang.shrballista+'', ''+culang.shrbatteringram+'', ''+culang.shrcatapult+'', ''+culang.shrbloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'',''+culang.shrflarcher+'', 'Hsr']; 
		var t = Tabs.Marches;
		clearTimeout (t.displayTimer);

		function clickShowRemaining (){
			checkBox = ById('idCheck2');
			if (checkBox.checked)
				Options.encRemaining = false;
			else
				Options.encRemaining = true;
			t.show2 ();
		}

		enc = {};
		numSlots = 0;

		if (matTypeof(Seed.queue_atkinc) != 'array'){
			for (k in Seed.queue_atkinc){
				march = Seed.queue_atkinc[k];
				if (march.marchType == 2){
					++numSlots;
					city = march.toCityId;
					from = march.fromPlayerId;
					if (!enc[city])
						enc[city] = {};
					if (!enc[city][from])
						enc[city][from] = [];
					s = {};
					s.knight = parseInt (march.knightCombat);
					s.marchId = k.substr(1);
					s.fromXCoord = march.fromXCoord;
					s.fromYCoord = march.fromYCoord;
					s.troops = [];
					for (i=1; i<18; i++){
						if (Options.encRemaining)
							s.troops[i] = parseInt (march['unit'+ i +'Return']);
						else
							s.troops[i] = parseInt (march['unit'+ i +'Count']);
					}
					enc[city][from].push (s);
				}
			}
		}
		s = '<div class=pdxStat>'+culang.marchEmbassyHead+' - <input type=button value="?" id=boaidemarches3 class=buttonHelp></div>';
		if (numSlots == 0){
			s += '<BR><CENTER><B><i>'+culang.marchEmbassyNoTroops+'</i></b></center>';
		} else {
			s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;} .entete{background:#efa9a9;}</style>';
			s += '<TABLE cellspacing=0 cellpadding=2 width=100%>\
      <tr><td class="entete"><u><b>'+culang.mainAction+'</b></u></td><td class="entete"><u><b>'+culang.mainCoordinate+'</b></u></td><td class="entete"><u><b>'+culang.marchEmbassyFromPlayer+'</b></u></td><td class="entete"><u><b>'+culang.mainKnights+'</b></u></td><td colspan=12 class="entete"><u><b>'+culang.mainTroops+'</b></u></td><td class="entete"><u><b>'+culang.marchEmbassyShortFoodUsage+'</b></u></td></tr>';

			tot = [];
			totent= 0;
			for (i=0; i<18; i++) {
				tot[i] = 0;

			}
			for (c in Cities.cities){
				dest = Cities.cities[c].id;
				if (enc[dest]){
					s+= '<TR><TD class="city" colspan=20 align=left><B>'+culang.mainCastle+' - ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
					for (p in enc[dest]){
						try {
							player = Seed.players['u'+p].n;
						} catch (err){
							player = '???';
						}
						for (m=0; m<enc[dest][p].length; m++){
							var march = enc[dest][p][m];
							knight = '';
							if (march.knight > 0)
								knight = ' '+ march.knight +'';
							s += '<TR align=left><td align=left width=12%><A onclick="r8x6Home('+ march.marchId +')" title="'+culang.marchEmbassySendHomeNote+'"><SPAN><img src="'+IMGdeleteButton+'"></span></a></td>\
              <TD align=left><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+march.fromXCoord+','+march.fromYCoord+')'+'</a></td>\
              <TD align=left width=25%>'+ player +' </td><td align=left>'+ knight+'</td><td colspan=12>'
							var g=0;
							for (i=1; i<18; i++){
								if (march.troops[i] > 0) {
									s += ''+ march.troops[i]  +' '+ names[i-1]  +'<br>';
								}
								tot[i] += march.troops[i];
								g+=parseInt(march.troops[i])*parseInt(uW.unitupkeeps[i]);

							}
							totent += g;
							s += '</td><td>';
							s += addCommas(g) + '</td></tr>';
						}
					}
				}
			}
			s += '<TR><TD colspan=20><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100%><tr><td colspan=1></td>';
			for (k=1; k<18; k++)
				s += '<TD width=6% align=center><img title="' + uW.unitcost['unt'+k][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+k+'_30.jpg></td>';

			s += '</tr>';
			s += '<TR align=center><TD class="tot" align=left width=10% rowspan=2><B>'+culang.mainHTotal+'</b></td>';
			for (i=1; i<18; i++)
				s+= '<TD class="tot">'+ addCommas(tot[i]) +'</td>';
			s += '</tr><td colspan=12><span class="boldRed">'+culang.marchEmbassyFoodUsage+'</span>: '+addCommas(totent)+' '+uW.g_js_strings.commonstr.food+'/'+culang.shortHour+'</td></table>';
		}

		s += '<BR><INPUT type=CHECKBOX id=idCheck2 '+ (Options.encRemaining?'':' CHECKED ') +'> '+culang.marchEmbassyShowOriginalTroops+'';
		s += '<BR><sup><span class="boldRed">'+culang.mainImportant+'</span>:</sup> <span class="helpText">'+culang.marchEmbassyShowOriginalTroopsNote+'</span></div>';
		t.marchDiv.innerHTML = s;
		checkBox = ById('idCheck2');
		ById('boaidemarches3').addEventListener('click', function(){  window.open(homePage+" ");    } , false);
		checkBox.addEventListener('click', clickShowRemaining, false);
		t.displayTimer = setTimeout (t.show2, 10000);
	},
	butSendHome : function (marchId){
		var t = Tabs.Marches;
		t.ajaxSendHome (marchId);
	},
	ajaxSendHome : function (marchId, notify){
		var march = Seed.queue_atkinc['m'+ marchId];
		if (march == null)
			return;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.mid = marchId;
		params.cid = march.toCityId;
		params.fromUid = march.fromPlayerId;
		params.fromCid = march.fromCityId;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/kickoutReinforcements.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok){
					var upkeep = 0;
					for (var i=1; i<18; i++)
						upkeep += parseInt(march["unit" + i + "Return"]) * parseInt(uW.unitupkeeps[i]);
					uW.seed.resources["city"+ march.toCityId].rec1[3] -= upkeep;
					if (parseInt(march.fromPlayerId) == parseInt(uW.tvuid)) {
						var mymarch = uW.seed.queue_atkp["city" + march.fromCityId]["m" + marchId];
						var marchtime = Math.abs(parseInt(mymarch.destinationUnixTime) - parseInt(mymarch.eventUnixTime));
						mymarch.returnUnixTime = unixTime() + marchtime;
						mymarch.marchStatus = 8;
					}
					delete uW.seed.queue_atkinc["m" + marchId];
					if (notify != null)
						notify(null);
				} else {
					if (notify != null)
						notify(rslt.errorMsg);
				}
			},
			onFailure: function () {
				if (notify != null)
					notify(rslt.errorMsg);
			},
		});
	},
	butRecall2 : function (marchId){
		var t = Tabs.Marches;
		t.ajaxRecall2 (marchId);
	},
	ajaxRecall2 : function (marchId, notify){
		var villeencours;
		for (var c=0; c<Cities.numCities; c++){
			var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
			if (matTypeof(que)=='array')
				continue;
			for (k in que){
				if (k == 'm'+marchId){
					villeencours = Cities.cities[c].id;
					break;
				}
			}
		}
		var march = Seed.queue_atkp["city" + villeencours]["m" + marchId];
		if (march == null){
			return;
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.mid = marchId;
		params.cid = villeencours;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/undefend.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok){
					if(rslt.updateSeed){
						uW.seed.queue_atkp["city"+params.cid]["m"+params.mid].marchStatus=8;
						var marchtime=parseInt(uW.seed.queue_atkp["city"+params.cid]["m"+params.mid].returnUnixTime)-parseInt(uW.seed.queue_atkp["city"+params.cid]["m"+params.mid].destinationUnixTime);
						var ut=uW.unixtime();
						if(uW.seed.playerEffects.returnExpire>ut){marchtime*=0.5}
						uW.seed.queue_atkp["city"+villeencours]["m"+marchId].destinationUnixTime=rslt.destinationUnixTime||ut;
						uW.seed.queue_atkp["city"+villeencours]["m"+marchId].returnUnixTime=rslt.returnUnixTime||ut+marchtime*rslt.returnMultiplier;
						uW.seed.queue_atkp["city"+villeencours]["m"+marchId].marchStatus=8;
						uW.update_seed(rslt.updateSeed)
					}
				}
			},
			onFailure: function () {
			},
		});

	},
	ajaxRecall : function (marchId, cid, notify){
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.mid = marchId;
		params.cid = cid;

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/cancelMarch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok){

					if(rslt.updateSeed){
						uW.seed.queue_atkp["city"+params.cid]["m"+params.mid].marchStatus=8;
						var marchtime=parseInt(uW.seed.queue_atkp["city"+params.cid]["m"+params.mid].returnUnixTime)-parseInt(uW.seed.queue_atkp["city"+params.cid]["m"+params.mid].destinationUnixTime);
						var ut=uW.unixtime();
						if(uW.seed.playerEffects.returnExpire>uW.unixtime()){marchtime*=0.5}
						uW.seed.queue_atkp["city"+cid]["m"+marchId].destinationUnixTime=rslt.destinationUnixTime||ut;
						uW.seed.queue_atkp["city"+cid]["m"+marchId].returnUnixTime=rslt.returnUnixTime||ut+marchtime*rslt.returnMultiplier;
						uW.seed.queue_atkp["city"+cid]["m"+marchId].marchStatus=8;
						uW.update_seed(rslt.updateSeed);
					}
					for(var j=1;j<18;j++){
						uW.seed.queue_atkp["city"+cid]["m"+marchId]["unit"+j+"Return"]=parseInt(uW.seed.queue_atkp["city"+cid]["m"+marchId]["unit"+j+"Count"])
					}
				}
			},
			onFailure: function () {
			},
		});

	},
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/TurboSearch.js">
//	
//	   KOC POWER - TABS TURBO SEARCH									        
//	

Tabs.TurboSearch = {
	tabOrder: TabOptions.toTurboSearch,
	tabLabel: culang.tabLabelTurboSearch,
	myDiv: null,
	tileTypes: {
		0: culang.kocBog,
		10: culang.kocGrassland,
		11: culang.kocLake,
		20: culang.kocWoods,
		30: culang.kocHill,
		40: culang.kocMount,
		50: culang.kocPlain,
		51: culang.kocCity,
		52: culang.kocRuin,
		53: culang.kocMistedCity,
		54: culang.kocDarkForest,
		55: "Mercenary Hideout"
	},
	rankings: {},
	provinces: {
		101: {
			x: 0,
			y: 0
		},
		102: {
			x: 150,
			y: 0
		},
		103: {
			x: 300,
			y: 0
		},
		104: {
			x: 450,
			y: 0
		},
		105: {
			x: 600,
			y: 0
		},
		106: {
			x: 0,
			y: 150
		},
		107: {
			x: 150,
			y: 150
		},
		108: {
			x: 300,
			y: 150
		},
		109: {
			x: 450,
			y: 150
		},
		110: {
			x: 600,
			y: 150
		},
		111: {
			x: 0,
			y: 300
		},
		112: {
			x: 150,
			y: 300
		},
		113: {
			x: 450,
			y: 300
		},
		114: {
			x: 600,
			y: 300
		},
		115: {
			x: 0,
			y: 450
		},
		116: {
			x: 150,
			y: 450
		},
		117: {
			x: 300,
			y: 450
		},
		118: {
			x: 450,
			y: 450
		},
		119: {
			x: 600,
			y: 450
		},
		120: {
			x: 0,
			y: 600
		},
		121: {
			x: 150,
			y: 600
		},
		122: {
			x: 300,
			y: 600
		},
		123: {
			x: 450,
			y: 600
		},
		124: {
			x: 600,
			y: 600
		},
	},
	userInfo: [],
	allianceNames: [],
	data: [],
	init: function (div) {
		var t = Tabs.TurboSearch;
		t.myDiv = div;
		uW.pbExportToRaid = t.ExportToRaid;
		//uW.GoToAttackTab = GoToAttackTab;
		var m = '<DIV class=pdxStat>' + culang.searchHead + '</div>';
		m += '<BR><B>' + culang.mainCastle + ' </b><SPAN id=TScityPick></span>&nbsp&nbsp&nbsp<b>X:</b>&nbsp<INPUT id=TSfromX maxlength=3 type=text>&nbsp&nbsp&nbsp<b>Y<:</b>&nbsp<INPUT id=TSfromY maxlength=3 type=text>';
		m += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<b>' + culang.searchArea + '</b> &nbsp<select id=TSselectRadius>';
		for (var i = 5; i <= 60; i += 5) m += '<option value=' + i + '>' + i + ' ' + culang.searchBlocks + '</option>';
		m += '<option value=' + null + '>--------------</option>';
		for (var i = 1; i <= 24; i++) m += '<option value=' + (100 + i) + '>' + uW.provincenames['p' + i] + '</option>';
		m += '</select>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT id=TSsearchButton type=submit class=pbButton value="' + culang.searchStart + '"> <span id="TSMAPError"></span>';
		m += '<BR><BR><DIV class=pdxStat><TABLE class=pdxTab width=350px align=center><TR><TD>' + culang.searchHeadResult + '</td><TD><INPUT id=TSscoutButton type=submit class=pbButton value="' + culang.searchHeadResultScout + '"></td><TD><INPUT id=TSShowMisted type=submit class=pbButton value="' + culang.searchHeadResultShowMisted + '"></td></tr></table></div>';
		m += '<TABLE id=TSleftMain width=100% class=pdxTab><TD style="vertical-align:top;"><DIV style="width:150px;max-width:150px;overflow:auto;" id=TSleft></div></td><TD style="text-align:left;vertical-align:top;"><DIV style="max-width:700px;max-height:450px;overflow:auto"id=TSright></div></td></table>';
		t.myDiv.innerHTML = m;
		t.from = new CdispCityPicker('pbSearchPicker', document.getElementById('TScityPick'), true, t.citySelNotify, 0);
		t.from.bindToXYboxes(document.getElementById('TSfromX'), document.getElementById('TSfromY'));
		document.getElementById('TSselectRadius')
			.value = 10;
		document.getElementById('TSsearchButton')
			.addEventListener('click', function () {
				var Radius = document.getElementById('TSselectRadius')
					.value;
				if (Radius == "null") return;
				if (document.getElementById('TSfromX')
					.value == "" && document.getElementById('TSfromY')
					.value == "") {
					alert("" + culang.searchPopSelCityOrCoords + "");
					return;
				}
				document.getElementById('TSsearchButton')
					.disabled = true;
				document.getElementById('TSsearchButton')
					.value = "" + culang.searchStartSearching + "";
				t.data = new Array();
				t.userInfo = {};
				t.allianceNames = {};
				if (Radius < 100) {
					var blocks = MakeBlocks(parseInt(document.getElementById('TSfromX')
						.value), parseInt(document.getElementById('TSfromY')
						.value), parseInt(document.getElementById('TSselectRadius')
						.value));
					t.doSearch(blocks, parseInt(document.getElementById('TSfromX')
						.value), parseInt(document.getElementById('TSfromY')
						.value), blocks.length, 1);
				}
				if (Radius > 100) {
					var blocks = MakeProvinceBlocks(t.provinces[Radius].x, t.provinces[Radius].y);
					t.doProvinceSearch(blocks, parseInt(document.getElementById('TSfromX')
						.value), parseInt(document.getElementById('TSfromY')
						.value), blocks.length, 1);
				}
			}, false);
		document.getElementById('TSscoutButton')
			.addEventListener('click', function () {
				var list = [];
				var element_class = document.getElementsByClassName('TSscout');
				for (k = 0; k < element_class.length; k++)
					if (element_class[k].checked) list.push(element_class[k].id);
				t.doAddScout(list);
			}, false);
		document.getElementById('TSShowMisted')
			.addEventListener('click', function () {
				var TodoList = new Array();
				for (var z = 0; z < t.data.length; z++)
					if (t.data[z].mapDat.cityName == "???") TodoList.push({
						x: t.data[z].mapDat.xCoord,
						y: t.data[z].mapDat.yCoord
					});
				t.CheckMistedCities(TodoList);
			}, false);
	},
	CheckCityMarches: function (cityID) {
		var Counter = 0;
		if (Seed.queue_atkp['city' + cityID] != undefined) {
			for (atkp in Seed.queue_atkp['city' + cityID])
				if (Seed.queue_atkp['city' + cityID][atkp]["marchUnixTime"]) Counter++;
		} else Counter = 0;
		return Counter;
	},
	CheckMistedCities: function (list) {
		var t = Tabs.TurboSearch;
		document.getElementById('TSright')
			.innerHTML = "";
		var m = '' + culang.searchResultsMistedCities + '<BR>';
		m += "<TABLE width=450px class=pdxTab><TR><TD><B><u>" + culang.searchResultsCoords + "</u></b></td><TD><B><u>" + culang.searchResultsPlayerName + "</u></b></td><TD><B><u>" + culang.searchResultsCityName + "</u></b></td></tr>";
		for (var i = 0; i < list.length; i++) m += '<TR><TD><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">(' + list[i].x + ',' + list[i].y + ')</a></td><TD><DIV id="TSmistPlayer_' + list[i].x + '_' + list[i].y + '"></div></td><TD><SPAN id="TSmistCity_' + list[i].x + '_' + list[i].y + '"></span></td></tr>';
		m += '</table>'
		document.getElementById('TSright')
			.innerHTML = m;
		t.FetchTileID(0, list.length, list)
	},
	FetchTileID: function (number, total, list) {
		var t = Tabs.TurboSearch;
		if (number == total) return;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = "bl_" + list[number].x + "_bt_" + list[number].y;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					for (var i in rslt.data)
						if (parseInt(rslt.data[i].xCoord) == list[number].x && parseInt(rslt.data[i].yCoord) == list[number].y) var tileId = parseInt(rslt.data[i].tileId)
					t.SetBookmark(number, total, list, tileId);
				}
			},
		});
	},
	SetBookmark: function (number, total, list, tileId) {
		var t = Tabs.TurboSearch;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.requestType = "BOOKMARK_LOCATION";
		params.tileId = tileId;
		params.bookmarkName = "Misted_City";
		new AjaxRequest(uW.g_ajaxpath + "ajax/tileBookmark.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) {
					try {
						uW.update_seed(rslt.updateSeed);
					} catch (e) {}
				}
				if (rslt.ok) t.GetBookmarkInfo(number, total, list);
			},
		});
	},
	GetBookmarkInfo: function (number, total, list) {
		var t = Tabs.TurboSearch;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.requestType = "GET_BOOKMARK_INFO";
		new AjaxRequest(uW.g_ajaxpath + "ajax/tileBookmark.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) {
					try {
						uW.update_seed(rslt.updateSeed);
					} catch (e) {}
				}
				if (rslt.ok) {
					for (var i in rslt.bookmarkInfo)
						if (parseInt(rslt.bookmarkInfo[i].xCoord) == list[number].x && parseInt(rslt.bookmarkInfo[i].yCoord) == list[number].y) {
							document.getElementById('TSmistPlayer_' + list[number].x + '_' + list[number].y)
								.innerHTML = rslt.bookmarkInfo[i].userName;
							document.getElementById('TSmistCity_' + list[number].x + '_' + list[number].y)
								.innerHTML = rslt.bookmarkInfo[i].cityName;
						}
					number++;
					setTimeout(t.FetchTileID, 750, number, total, list);
					t.RemoveBookMark(number, list, rslt.bookmarkInfo[i].bookmarkId);
				}
			},
		});
	},
	RemoveBookMark: function (number, list, bookmarkId) {
		var t = Tabs.TurboSearch;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.requestType = "REMOVE_BOOKMARK";
		params.bookmarkId = bookmarkId;
		new AjaxRequest(uW.g_ajaxpath + "ajax/tileBookmark.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) {
					try {
						uW.update_seed(rslt.updateSeed);
					} catch (e) {}
				}
				if (rslt.ok) {}
			},
		});
	},
	doAddAttack: function (list) {
		var t = Tabs.TurboSearch;
		for (var k = 0; k < list.length; k++) {
			var coords = list[k].substr(14);
			var array = coords.split(',');
			if (array[0] != undefined && array[1] != undefined) {
				var x = array[0];
				var y = array[1];
			}
		}
	},
	GetCoords: function () {
		var t = Tabs.Transport;
		var targetName = "";
		var targetCityName = "";
		var total = 0;
		var units = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
		targetX = parseInt(document.getElementById('ptcityX')
			.value);
		targetY = parseInt(document.getElementById('ptcityY')
			.value);
		if (targetX == "" || targetY == "") {
			alert("" + culang.searchTransportEnterCoords + "");
			return;
		}
		var what = document.getElementById('TransportTroop')
			.value;
		what = what.substr(3);
		if (parseInt(document.getElementById('TroopsToSend')) == 0) {
			alert("" + culang.searchTransportLeastOneTroop + "");
			return;
		}
		units[what] = parseInt(document.getElementById('TroopsToSend')
			.value);
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = "bl_" + targetX + "_bt_" + targetY;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					if (rslt.data["l_" + targetX + "_t_" + targetY].tileType == 51) {
						userId = rslt.data["l_" + targetX + "_t_" + targetY].tileUserId;
						if (userId != null) targetName = rslt.userInfo["u" + userId]["n"];
						targetCityName = rslt.data["l_" + targetX + "_t_" + targetY].cityName;
					}
					MarchOptions.Queue.push({
						city: t.tcp.city.id,
						action: 1,
						targetX: targetX,
						targetY: targetY,
						tileType: rslt.data["l_" + targetX + "_t_" + targetY].tileType,
						tileLevel: rslt.data["l_" + targetX + "_t_" + targetY].tileLevel,
						targetCityName: targetCityName,
						targetName: targetName,
						cityNumber: rslt.data["l_" + targetX + "_t_" + targetY].cityNum,
						1: units[1],
						2: units[2],
						3: units[3],
						4: units[4],
						5: units[5],
						6: units[6],
						7: units[7],
						8: units[8],
						9: units[9],
						10: units[10],
						11: units[11],
						12: units[12],
						13: units[13],
						14: units[14],
						15: units[15],
						16: units[16],
						r1: parseInt(document.getElementById('pbtradeamountFood')
							.value),
						r2: parseInt(document.getElementById('pbtradeamountWood')
							.value),
						r3: parseInt(document.getElementById('pbtradeamountStone')
							.value),
						r4: parseInt(document.getElementById('pbtradeamountOre')
							.value),
						r5: parseInt(document.getElementById('pbtradeamountAstone')
							.value),
						gold: parseInt(document.getElementById('pbtradeamountGold')
							.value)
					});
					saveMarchOptions();
					document.getElementById('TroopsToSend')
						.value = 0;
					document.getElementById('pbtradeamountFood')
						.value == 0;
					document.getElementById('pbtradeamountWood')
						.value == 0;
					document.getElementById('pbtradeamountStone')
						.value == 0;
					document.getElementById('pbtradeamountOre')
						.value == 0;
					document.getElementById('pbtradeamountAstone')
						.value == 0;
					document.getElementById('pbtradeamountGold')
						.value == 0;
					Dashboard.ShowMarches();
				}
			},
		});
	},
	doAddScout: function (list) {
		var t = Tabs.TurboSearch;
		var count = -1;
		var city = "";
		slots = t.CheckCityMarches(t.from.city.id);
		rallypointlevel = getRallypoint(t.from.city.id);
		for (var k = 0; k < list.length; k++) {
			var coords = list[k].substr(14);
			var array = coords.split(',');
			if (array[0] != undefined && array[1] != undefined) {
				var x = array[0];
				var y = array[1];
				count++;
				setTimeout(t.doScout, 1500 * count, x, y, list[k]);
			}
		}
	},
	doScout: function (x, y, box) {
		var t = Tabs.TurboSearch;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid = t.from.city.id;
		params.type = 3
		params.kid = 0
		params.xcoord = x;
		params.ycoord = y;
		params.u3 = 1;
		params.gold = 0;
		params.r1 = 0;
		params.r2 = 0;
		params.r3 = 0;
		params.r4 = 0;
		params.r5 = 0;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				var t = Tabs.Player;
				if (rslt.ok) {
					var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
					var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
					for (i = 0; i <= unitsarr.length; i++) {
						if (params["u" + i]) {
							unitsarr[i] = params["u" + i];
						}
					}
					var resources = new Array();
					resources[0] = params.gold;
					for (i = 1; i <= 4; i++) {
						resources[i] = params["r" + i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
					if (rslt.updateSeed) {
						uW.update_seed(rslt.updateSeed)
					};
					document.getElementById(box)
						.checked = false;
				}
			},
			onFailure: function () {},
		});
	},
	searchDone: function (data, userInfo, allianceNames, fromX, fromY, ProvinceSearch) {
		var t = Tabs.TurboSearch;
		var dist = 0;
		mapDat = [];
		for (var i in data) {
			dist_i = distance(fromX, fromY, data[i].xCoord, data[i].yCoord)
			mapDat.push({
				xCoord: data[i].xCoord,
				yCoord: data[i].yCoord,
				dist: dist_i,
				tileType: data[i].tileType,
				tileLevel: data[i].tileLevel,
				tileUserId: data[i].tileUserId,
				cityName: data[i].cityName,
				tileCityId: data[i].tileCityId,
				cityNum: data[i].cityNum,
			});
		}
		mapDat = mapDat.sort(function sort(a, b) {
			a = a['dist'];
			b = b['dist'];
			return a == b ? 0 : (a < b ? -1 : 1);
		});
		var checked = ((ProvinceSearch) ? "unchecked" : "checked");
		var left = '<BR><input id=RadioCities type="radio" name="TStypes" value="Cities">' + culang.searchCities + '';
		left += '<BR><input id=RadioBarb type="radio" name="TStypes" value="Barb Camps">' + culang.searchBarbCamps + '';
		left += '<BR><input id=RadioWild type="radio" name="TStypes" value="Wilderness">' + culang.searchWilderness + '';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<select id=TSwildType>';
		left += '<option value=ALL>' + culang.mainAll + '</option><option value=99>' + culang.searchGrassLake + '</option><option value=20>' + culang.searchWoodland + '</option><option value=30>' + culang.searchHills + '</option><option value=40>' + culang.searchMountain + '</option><option value=50>' + culang.searchPlain + '</option><option value=54>' + culang.searchDarkForest + '</option></select>';
		left += '<BR>___________________<BR>';
		left += '<INPUT type=checkbox id=TSunowned checked=true><SPAN id=DIVunowned></span>';
		left += '<BR><SPAN id=DIVminLevel></span><select id=TSminLevel>';
		for (var i = 1; i <= 10; i++) left += '<option value=' + i + '>' + i + '</option>';
		left += '</select><BR><SPAN id=DIVmaxLevel></span><select id=TSmaxLevel>';
		for (var i = 1; i <= 10; i++) left += '<option value=' + i + '>' + i + '</option>';
		left += '</select>';
		left += '<BR>___________________<BR>';
		left += '<INPUT type=checkbox id=TSallied checked=true><SPAN id=DIVallied></span>';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp<INPUT type=checkbox id=TSmisted checked=true><SPAN id=DIVmisted></span>';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp<INPUT type=checkbox id=TShostile ' + checked + '><SPAN id=DIVhostile></span>';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp<INPUT type=checkbox id=TSfriendly ' + checked + '><SPAN id=DIVfriendly></span>';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp<INPUT type=checkbox id=TSfriendlyToUs ' + checked + '><SPAN id=DIVfriendlyToUs></span>';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp<INPUT type=checkbox id=TSneutral ' + checked + '><SPAN id=DIVneutral></span>';
		left += '<BR><INPUT type=checkbox id=TSunAllied ' + checked + '><SPAN id=DIVunAllied></span>';
		left += '<BR><BR><SPAN id=DIVmight></span>';
		left += '<BR><SPAN id=DIVmightMin></span><INPUT id=TSmightMin size=4 maxlength=4 type=text value=' + parseInt(Options.SearchMightMin) + '>';
		left += '<BR><SPAN id=DIVmightMax></span><INPUT id=TSmightMax size=4 maxlength=4 type=text value=' + parseInt(Options.SearchMightMax) + '>';
		left += '<BR><BR><INPUT type=checkbox id=TSfilerTop disabled=true unchecked=true><SPAN id=DIVfilterTop></span>';
		left += '<BR>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<select id=TStopMin>';
		for (var i = 1; i <= 19; i++) left += '<option value=' + i + '>' + i + '</option><';
		left += '</select>&nbsp&nbsp<SPAN id=DIVtop></span>&nbsp&nbsp<select id=TStopMax>';
		for (var i = 2; i <= 20; i++) left += '<option value=' + i + '>' + i + '</option>';
		left += '</select>';
		document.getElementById('TSleft')
			.innerHTML = left;
		document.getElementById('TSsearchButton')
			.value = "" + culang.searchStart + "";
		document.getElementById('TSsearchButton')
			.disabled = false;
		document.getElementById('TSminLevel')
			.addEventListener('change', function () {
				Options.srcMinLevel = document.getElementById('TSminLevel')
					.value;
				saveOptions();
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSmaxLevel')
			.addEventListener('change', function () {
				Options.srcMaxLevel = document.getElementById('TSmaxLevel')
					.value;
				saveOptions();
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSmightMin')
			.addEventListener('change', function () {
				Options.SearchMightMin = document.getElementById('TSmightMin')
					.value;
				saveOptions();
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSmightMax')
			.addEventListener('change', function () {
				Options.SearchMightMax = document.getElementById('TSmightMax')
					.value;
				saveOptions();
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSfilerTop')
			.addEventListener('change', function () {
				if (document.getElementById('TSfilerTop')
					.disabled) {
					document.getElementById('TStopMin')
						.disabled = true;
					document.getElementById('TStopMax')
						.disabled = true;
					document.getElementById('DIVfilterTop')
						.innerHTML = '<i><FONT color=grey>' + culang.searchFilterAlliancesRank + '</font></i>';
					document.getElementById('DIVtop')
						.innerHTML = '<FONT color=grey>' + culang.searchFilterTo + '</font>';
				} else {
					document.getElementById('TStopMin')
						.disabled = false;
					document.getElementById('TStopMax')
						.disabled = false;
					document.getElementById('DIVfilterTop')
						.innerHTML = '<i><FONT color=black>' + culang.searchFilterAlliancesRank + '</font></i>';
					document.getElementById('DIVtop')
						.innerHTML = '<FONT color=black>' + culang.searchFilterTo + '</font>';
				}
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('RadioCities')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('RadioBarb')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('RadioWild')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSwildType')
			.addEventListener('change', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSunowned')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSmisted')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TShostile')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSfriendly')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSfriendlyToUs')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSneutral')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSallied')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TSunAllied')
			.addEventListener('click', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TStopMin')
			.addEventListener('change', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('TStopMax')
			.addEventListener('change', function () {
				t.checkData(mapDat, userInfo, allianceNames, fromX, fromY);
			}, false);
		document.getElementById('RadioCities')
			.checked = true;
		document.getElementById('TSminLevel')
			.value = Options.srcMinLevel;
		document.getElementById('TSmaxLevel')
			.value = Options.srcMaxLevel;
		document.getElementById('TStopMin')
			.value = 1;
		document.getElementById('TStopMax')
			.value = 10;
		t.checkData(mapDat, userInfo, allianceNames, fromX, fromY)
	},
	checkData: function (mapDat, userInfo, allianceNames, fromX, fromY) {
		var t = Tabs.TurboSearch;
		t.checkOptions();
		t.data = new Array();
		var Dip = Seed.allianceDiplomacies;
		var data = "<TABLE id=KsTurboSearch width=100% class=pdxTab>";
		data += '<TR><TD><INPUT id=CheckAll type=checkbox unchecked=true></td><TD><B><u>' + culang.searchResultsCoords + '</u></b></td><TD><B><u>' + culang.searchResultsDist + '</u></b></td><TD><B><u>' + culang.searchResultsType + '</u></b></td><TD><B><u>' + culang.searchResultsLev + '</u></b></td><TD><B><u>' + uW.g_js_strings.commonstr.might + '</b></u></td><TD>&nbsp</td><TD><B><u>' + culang.mainPlayer + '</u></b></td><TD><B><u>' + culang.mainName + '</u></b></td><TD><u><B>' + uW.g_js_strings.commonstr.alliance + '</b></u></td></tr>';
		var LastX = 0;
		var LastY = 0;
		for (var i in mapDat) {
			if (mapDat[i].xCoord != undefined) {
				var tileType = parseInt(mapDat[i].tileType);
				if (document.getElementById('RadioCities')
					.checked) {
					if ((tileType == 51 || tileType == 53) && mapDat[i].tileCityId != null) {
						var allianceID = 0;
						if (userInfo['u' + mapDat[i].tileUserId]) allianceID = parseInt(userInfo['u' + mapDat[i].tileUserId]["a"]);
						var diplomacy = 0;
						var Might = 0;
						if (userInfo['u' + mapDat[i].tileUserId]) Might = Math.round(userInfo['u' + mapDat[i].tileUserId]["m"]);
						var misted, hostile, friendly, friendlyToUs, neutral, allied, mightCheck, A_check;
						misted = hostile = friendly = friendlyToUs = neutral = allied = mightCheck = A_check = false;
						var top = true;
						if (Dip.friendly && Dip.friendly['a' + allianceID]) diplomacy = 1;
						if (Dip.hostile && Dip.hostile['a' + allianceID]) diplomacy = 2;
						if (Dip.friendlyToYou && Dip.friendlyToYou['a' + allianceID]) diplomacy = 3;
						if (Dip.allianceId == allianceID) diplomacy = 1;
						if (allianceID > 0 || tileType == 53) allied = true;
						if (Might >= (Options.SearchMightMin * 1000000) && Might <= (Options.SearchMightMax * 1000000)) mightCheck = true;
						if (document.getElementById('TSallied')
							.checked && allied) A_check = true;
						else if (document.getElementById('TSallied')
							.checked && allied) A_check = false;
						if (document.getElementById('TSunAllied')
							.checked && !allied) A_check = true;
						else if (document.getElementById('TSunAllied')
							.checked && !allied) A_check = false;
						if (document.getElementById('TSmisted')
							.checked && tileType == 53) misted = true;
						else if (document.getElementById('TSmisted')
							.checked && tileType == 51) misted = false;
						if (document.getElementById('TShostile')
							.checked && diplomacy == 2) hostile = true;
						else if (document.getElementById('TShostile')
							.checked && tileType == 2) hostile = false;
						if (document.getElementById('TSfriendly')
							.checked && diplomacy == 1) friendly = true;
						else if (document.getElementById('TSfriendly')
							.checked && tileType == 1) friendly = false;
						if (document.getElementById('TSfriendlyToUs')
							.checked && diplomacy == 3) friendlyToUs = true;
						else if (document.getElementById('TSfriendlyToUs')
							.checked && tileType == 3) friendlyToUs = false;
						if (document.getElementById('TSneutral')
							.checked && diplomacy == 0) neutral = true;
						else if (document.getElementById('TSneutral')
							.checked && tileType == 0) neutral = false;
						if (!allied) neutral = true;
						if (misted) mightCheck = true;
						if (document.getElementById('TSfilerTop')
							.checked &&
							t.rankings[allianceID] >= document.getElementById('TStopMin')
							.value &&
							t.rankings[allianceID] <= document.getElementById('TStopMax')
							.value) top = false;
						var unique = true;
						if (parseInt(mapDat[i].xCoord) == LastX && parseInt(mapDat[i].yCoord) == LastY) unique = false;
						LastX = parseInt(mapDat[i].xCoord);
						LastY = parseInt(mapDat[i].yCoord);
						if ((misted || hostile || friendly || friendlyToUs || neutral) && A_check && mightCheck && top && unique) data += t.paintData(mapDat[i], userInfo, allianceNames, fromX, fromY);
					}
				}
				if (document.getElementById('RadioBarb')
					.checked) {
					if (tileType == 51 && mapDat[i].tileCityId == null && parseInt(mapDat[i].tileLevel) >= Options.srcMinLevel && parseInt(mapDat[i].tileLevel) <= Options.srcMaxLevel) data += t.paintData(mapDat[i], userInfo, allianceNames, fromX, fromY);
				}
				if (document.getElementById('RadioWild')
					.checked && tileType != 51 && tileType != 53) {
					if (document.getElementById('TSunowned')
						.checked && mapDat[i].tileCityId == null) var unownedOnly = true;
					else if (document.getElementById('TSunowned')
						.checked) var unownedOnly = false;
					else var unownedOnly = true;
					var filter = document.getElementById('TSwildType')
						.value;
					if ((tileType == 10 || tileType == 11) && filter == 99)
						if (unownedOnly && parseInt(mapDat[i].tileLevel) >= Options.srcMinLevel && parseInt(mapDat[i].tileLevel) <= Options.srcMaxLevel) data += t.paintData(mapDat[i], userInfo, allianceNames, fromX, fromY);
					if (tileType == filter && unownedOnly && parseInt(mapDat[i].tileLevel) >= Options.srcMinLevel && parseInt(mapDat[i].tileLevel) <= Options.srcMaxLevel) data += t.paintData(mapDat[i], userInfo, allianceNames, fromX, fromY);
					if (filter == "ALL" && unownedOnly && parseInt(mapDat[i].tileLevel) >= Options.srcMinLevel && parseInt(mapDat[i].tileLevel) <= Options.srcMaxLevel) data += t.paintData(mapDat[i], userInfo, allianceNames, fromX, fromY);
				}
			}
		}
		document.getElementById('TSright')
			.innerHTML = data;
		document.getElementById('CheckAll')
			.addEventListener('change', t.doSelectall, false);
		var uList = [];
		for (k in mapDat)
			if (mapDat[k].tileUserId != null) uList.push(mapDat[k].tileUserId);
		t.fetchPlayerStatus(uList);
	},
	doSelectall: function () {
		var t = Tabs.TurboSearch;
		var element_class = document.getElementsByClassName('TSscout');
		for (k = 0; k < element_class.length; k++)((element_class[k].checked) ? element_class[k].checked = false : element_class[k].checked = true)
	},
	paintData: function (mapDat, userInfo, allianceNames, fromX, fromY) {
		var t = Tabs.TurboSearch;
		var Dip = Seed.allianceDiplomacies;
		t.data.push({
			mapDat: mapDat
		})
		//Checkbox
		data = '<TR><TD><INPUT class=TSscout id=ScoutCheckbox_' + mapDat.xCoord + "," + mapDat.yCoord + ' type=checkbox unchecked=true></td>';
		//Coords
		data += '<TD><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">(' + mapDat.xCoord + ',' + mapDat.yCoord + ')</a></td>';
		//Distance
		data += '<TD>' + mapDat.dist + '</td>';
		//Tile Type
		var tileType = parseInt(mapDat.tileType);
		if (tileType == 51 && mapDat.tileCityId == null) tileType = 'Barb Camp';
		else tileType = t.tileTypes[parseInt(mapDat.tileType)];
		data += '<TD>' + tileType;
		if (parseInt(mapDat.tileType) == 51 && mapDat.tileCityId != null) data += ' (' + mapDat.cityNum + ')';
		data += '</td>';
		//Tile Level
		if (mapDat.tileLevel > 0) data += '<TD>' + mapDat.tileLevel + '</td>';
		else data += '<TD>??</td>';
		//Might
		if (mapDat.tileUserId != null && mapDat.tileUserId != 0) data += '<TD align=right>' + addCommas(Math.round(parseInt(userInfo['u' + mapDat.tileUserId]["m"]))) + '</td>';
		else data += '<TD></td>';
		//Space
		data += '<TD>&nbsp</td>';
		//Player
		if (mapDat.tileUserId != null && mapDat.tileUserId != 0) data += '<TD><SPAN class="DIVonline_' + mapDat.tileUserId + '"></span>' + userInfo['u' + mapDat.tileUserId]["n"] + '</td>';
		else if (mapDat.tileUserId == 0) data += '<TD>???</td>';
		else data += '<TD>---</td>';
		//City Name
		if (mapDat.cityName != null) data += '<TD>' + mapDat.cityName + '</td>';
		else if (mapDat.tileUserId == 0) data += '<TD>???</td>';
		else data += '<TD>---</td>';
		//Alliance Name
		if (mapDat.tileUserId != null && mapDat.tileUserId != 0) {
			var allianceID = userInfo['u' + mapDat.tileUserId]["a"];
			if (allianceID != 0) {
				var color = "black";
				if (Dip.friendly && Dip.friendly['a' + allianceID]) color = "green";
				if (Dip.hostile && Dip.hostile['a' + allianceID]) color = "red";
				if (Dip.friendlyToYou && Dip.friendlyToYou['a' + allianceID]) color = "orange";
				if (Dip.allianceId == allianceID) color = "blue";
				data += '<TD><FONT color=' + color + '>' + allianceNames['a' + allianceID] + '</font></td>';
			} else data += '<TD>---</td>';
		} else if (mapDat.tileUserId == 0) data += '<TD>???</td>';
		else if (parseInt(mapDat.tileType) == 51 && mapDat.tileCityId == null) data += '<TD><A onclick="pbExportToRaid(' + mapDat.xCoord + ',' + mapDat.yCoord + ')">' + culang.searchRaidExport + '</td>';
		else data += '<TD>---</td>';
		return data;
	},
	ExportToRaid: function (X, Y) {
		var t = Tabs.TurboSearch;
		var cityId = t.from.city.id;
		var pop = new CPopup('pbExportRaid', 0, 0, 750, 255, true);
		if (t.popFirst) {
			pop.centerMe(mainPop.getMainDiv());
			t.popFirst = false;
		}
		pop.getTopDiv()
			.innerHTML = '<div class="popupBanner">' + culang.searchRaidPopExport + '</div>';
		var m = '<TABLE id=pbRaidAdd width=100% height=0% class=pdxTab><TR>';
		for (i = 1; i <= 5; i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_30.jpg"><TD align=left>' + addCommas(Seed.units['city' + cityId]['unt' + i]) + '</td>';
		m += '</tr><TR>';
		for (i = 1; i <= 5; i++) m += '<TD><INPUT id="Unit' + i + '" type=text size=6 maxlength=6 value="0"></td>';
		m += '</tr><TR>';
		for (i = 6; i <= 10; i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_30.jpg"><TD align=left>' + addCommas(Seed.units['city' + cityId]['unt' + i]) + '</td>';
		m += '</tr><TR>';
		for (i = 6; i <= 10; i++) m += '<TD><INPUT id="Unit' + i + '" type=text size=6 maxlength=6 value="0"></td>';
		m += '</tr><TR>';
		for (i = 11; i <= 15; i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_30.jpg"><TD align=left>' + addCommas(Seed.units['city' + cityId]['unt' + i]) + '</td>';
		m += '</tr><TR>';
		for (i = 11; i <= 15; i++) m += '<TD><INPUT id="Unit' + i + '" type=text size=6 maxlength=6 value="0"></td>';
		m += '</tr></table>';
		m += '<BR><CENTER><input id=pbHelp type=submit  value="' + culang.buttonHelp + '"> <SELECT id=RaidKnights type=list></select></center>';
		m += '<BR><CENTER><input id=pbRaidSave type=submit  value="' + culang.searchRaidSave + '"></center>';
		pop.getMainDiv()
			.innerHTML = m;
		t.getKnights();
		document.getElementById('pbHelp')
			.addEventListener('click', t.helpPop, false);
		document.getElementById('pbRaidSave')
			.addEventListener('click', function () {
				var params = uW.Object.clone(uW.g_ajaxparams);
				params.pf = 0;
				params.ctrl = 'BotManager';
				params.action = 'saveMarch';
				params.settings = {};
				params.settings.cityId = cityId;
				params.queue = {
					0: {
						botMarches: {
							botMarchStatus: 1,
							botState: 1
						},
						cityMarches: {}
					}
				};
				params.queue[0].cityMarches.knightId = parseInt(document.getElementById('RaidKnights')
					.value);
				params.queue[0].cityMarches.toXCoord = X;
				params.queue[0].cityMarches.toYCoord = Y;
				params.queue[0].cityMarches.unit0Count = 0;
				for (var i = 1; i <= 15; i++) params.queue[0].cityMarches['unit' + i + 'Count'] = parseInt(document.getElementById('Unit' + i)
					.value);
				new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					loading: true,
					onSuccess: function (transport) {
						var rslt = eval("(" + transport.responseText + ")");
						if (rslt.updateSeed) {
							try {
								uW.update_seed(rslt.updateSeed);
							} catch (e) {}
						}
						if (rslt.ok) {
							pop.show(false);
							uW.cityinfo_army();
							setTimeout(uW.update_seed_ajax, 250);
						} else alert('Error :' + rslt.msg);
					},
				});
			}, false);
		pop.show(true);
	},
	getKnights: function () {
		var t = Tabs.TurboSearch;
		var knt = new Array();
		cityId = t.from.city.id;
		for (k in Seed.knights['city' + cityId]) {
			if (Seed.knights['city' + cityId][k]["knightStatus"] == 1 && Seed.leaders['city' + cityId]["resourcefulnessKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["politicsKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["combatKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["intelligenceKnightId"] != Seed.knights['city' + cityId][k]["knightId"]) {
				knt.push({
					Name: Seed.knights['city' + cityId][k]["knightName"],
					Combat: parseInt(Seed.knights['city' + cityId][k]["combat"]),
					ID: Seed.knights['city' + cityId][k]["knightId"],
				});
			}
		}
		knt = knt.sort(function sort(a, b) {
			a = a['Combat'];
			b = b['Combat'];
			return a == b ? 0 : (a > b ? -1 : 1);
		});
		document.getElementById('RaidKnights')
			.options.length = 0;
		var o = document.createElement("option");
		o.text = '' + culang.searchKnightSelect + '';
		o.value = 0;
		document.getElementById("RaidKnights")
			.options.add(o);
		for (k in knt) {
			if (knt[k]["Name"] != undefined) {
				var o = document.createElement("option");
				o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] + ')')
				o.value = knt[k]["ID"];
				document.getElementById("RaidKnights")
					.options.add(o);
			}
		}
	},
	helpPop: function () {
		var helpText = culang.searchPopRaids;
		var pop = new CPopup('giftHelp', 0, 0, 400, 350, true);
		pop.centerMe(mainPop.getMainDiv());
		pop.getMainDiv()
			.innerHTML = helpText;
		pop.getTopDiv()
			.innerHTML = '<div class="popupBanner">' + culang.searchHeadPopRaids + '</div>';
		pop.show(true);
	},
	doSearch: function (blocks, fromX, fromY, number, count) {
		var t = Tabs.TurboSearch;
		document.getElementById('TSsearchButton').value = count + '/' + Math.ceil(number / 20);
		if (blocks.length <= 0) {
			t.searchDone(t.data, t.userInfo, t.allianceNames, fromX, fromY, false);
			return;
		}
		count++;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.blocks = blocks.splice(0, 20);
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				try {
					if (rslt.ok) {
						if (rslt.error_code == 9) {
							//Map Error
							ById('TSMAPError').innerHTML = 'Map Error';
							setTimeout(function() {ById('TSMAPError').innerHTML = '';},5000);
							t.searchDone(t.data, t.userInfo, t.allianceNames, fromX, fromY, false);
							return;
						}	
						for (var r in rslt.data) t.data.push(rslt.data[r]);
						for (var r in rslt.userInfo) {
							t.userInfo[r] = rslt.userInfo[r]
						};
						for (var r in rslt.allianceNames) {
							t.allianceNames[r] = rslt.allianceNames[r]
						};
						setTimeout(t.doSearch, 500, blocks, fromX, fromY, number, count);
						
					} else {
						alert('Search Failed');
					}
				} catch (ex) {
					alert('8250/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
				}
			},
			onFailure: function () {
				alert('Search Failed');
				document.getElementById('TSsearchButton').value = "Start Search";
				document.getElementById('TSsearchButton').disabled = false;
			},
		});
	},
	doProvinceSearch: function (blocks, fromX, fromY, number, count) {
		var t = Tabs.TurboSearch;
		document.getElementById('TSsearchButton')
			.value = count + '/' + Math.ceil(number / 20);
		if (blocks.length <= 0) {
			t.searchDone(t.data, t.userInfo, t.allianceNames, fromX, fromY, true);
			return;
		}
		count++;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.blocks = blocks.splice(0, 20);
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				try {
					if (rslt.ok) {
						if (rslt.error_code == 9) {
							//Map Error
							ById('TSMAPError').innerHTML = 'Map Error';
							setTimeout(function() {ById('TSMAPError').innerHTML = '';},5000);
							t.searchDone(t.data, t.userInfo, t.allianceNames, fromX, fromY, true);
							return;
						}	
						for (var r in rslt.data) t.data.push(rslt.data[r]);
						for (var r in rslt.userInfo) {
							t.userInfo[r] = rslt.userInfo[r]
						};
						for (var r in rslt.allianceNames) {
							t.allianceNames[r] = rslt.allianceNames[r]
						};
						setTimeout(t.doProvinceSearch, 500, blocks, fromX, fromY, number, count);
						
					} else {
						alert('Search Failed');
					}
				} catch (ex) {
					alert('8297/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
				}
			},
			onFailure: function () {
				alert('Search Failed');
				document.getElementById('TSsearchButton').value = "Start Search";
				document.getElementById('TSsearchButton').disabled = false;
			},
		});
	},
	fetchPlayerStatus: function (uidArray) {
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.checkArr = uidArray.join(',');
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/getOnline.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok)
					for (var y in rslt.data) {
						if (rslt.data[y]) var status = '<img src=""/>';
						else var status = '<img src=""/>';
						var element = document.getElementsByClassName('DIVonline_' + y);
						for (var k = 0; k < element.length; k++) element[k].innerHTML = status;
					}
			},
			onFailure: function () {},
		});
	},
	checkOptions: function () {
		var t = Tabs.TurboSearch;
		if (document.getElementById('RadioCities')
			.checked) {
			document.getElementById('DIVminLevel')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterMinLev + ' </font>';
			document.getElementById('DIVmaxLevel')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterMaxLev + ' </font>';
			document.getElementById('DIVunowned')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterUnowned + '</font>';
			document.getElementById('TSunowned')
				.disabled = true;
			document.getElementById('TSminLevel')
				.disabled = true;
			document.getElementById('TSmaxLevel')
				.disabled = true;
			t.enableCityOptions();
		}
		if (document.getElementById('RadioBarb')
			.checked || document.getElementById('RadioWild')
			.checked) {
			document.getElementById('DIVminLevel')
				.innerHTML = '<FONT color=black>' + culang.searchFilterMinLev + ' </font>';
			document.getElementById('DIVmaxLevel')
				.innerHTML = '<FONT color=black>' + culang.searchFilterMaxLev + ' </font>';
			if (document.getElementById('RadioBarb')
				.checked) {
				document.getElementById('DIVunowned')
					.innerHTML = '<FONT color=grey>' + culang.searchFilterUnowned + '</font>';
				document.getElementById('TSunowned')
					.disabled = true;
			} else {
				document.getElementById('DIVunowned')
					.innerHTML = '<FONT color=black>' + culang.searchFilterUnowned + '</font>';
				document.getElementById('TSunowned')
					.disabled = false;
			}
			document.getElementById('TSminLevel')
				.disabled = false;
			document.getElementById('TSmaxLevel')
				.disabled = false;
			t.disableCityOptions();
		}
	},
	disableCityOptions: function () {
		document.getElementById('DIVmisted')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterMisted + '</font>';
		document.getElementById('DIVhostile')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterHostile + '</font>';
		document.getElementById('DIVfriendly')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterFriendlyUs + '</font>';
		document.getElementById('DIVfriendlyToUs')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterFriendlyToUs + '</font>';
		document.getElementById('DIVneutral')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterNeutral + '</font>';
		document.getElementById('DIVallied')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterAllied + '</font>';
		document.getElementById('DIVunAllied')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterUnallied + '</font>';
		document.getElementById('DIVmight')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterMightInMillion + '</font>';
		document.getElementById('DIVmightMin')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterMin + '</font>';
		document.getElementById('DIVmightMax')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterMax + '</font>';
		document.getElementById('DIVfilterTop')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterAlliancesRank + '</font>';
		document.getElementById('DIVtop')
			.innerHTML = '<FONT color=grey>' + culang.searchFilterTo + '</font>';
		document.getElementById('TSmisted')
			.disabled = true;
		document.getElementById('TShostile')
			.disabled = true;
		document.getElementById('TSfriendly')
			.disabled = true;
		document.getElementById('TSfriendlyToUs')
			.disabled = true;
		document.getElementById('TSneutral')
			.disabled = true;
		document.getElementById('TSallied')
			.disabled = true;
		document.getElementById('TSunAllied')
			.disabled = true;
		document.getElementById('TSmightMin')
			.disabled = true;
		document.getElementById('TSmightMax')
			.disabled = true;
		document.getElementById('TSfilerTop')
			.disabled = true;
		document.getElementById('TStopMin')
			.disabled = true;
		document.getElementById('TStopMax')
			.disabled = true;
	},
	enableCityOptions: function () {
		if (document.getElementById('TSallied')
			.checked) {
			document.getElementById('TSmisted')
				.disabled = false;
			document.getElementById('TShostile')
				.disabled = false;
			document.getElementById('TSfriendly')
				.disabled = false;
			document.getElementById('TSfriendlyToUs')
				.disabled = false;
			document.getElementById('TSneutral')
				.disabled = false;
			document.getElementById('DIVmisted')
				.innerHTML = '<FONT color=black>' + culang.searchFilterMisted + '</font>';
			document.getElementById('DIVhostile')
				.innerHTML = '<FONT color=red>' + culang.searchFilterHostile + '</font>';
			document.getElementById('DIVfriendly')
				.innerHTML = '<FONT color=green>' + culang.searchFilterFriendly + '</font>&nbsp/&nbsp<FONT color=blue>' + culang.searchFilterFriendly2 + '</font>';
			document.getElementById('DIVfriendlyToUs')
				.innerHTML = '<FONT color=orange>' + culang.searchFilterFriendlyToUs + '</font>';
			document.getElementById('DIVneutral')
				.innerHTML = '<FONT color=black>' + culang.searchFilterNeutral + '</font>';
		} else {
			document.getElementById('TSmisted')
				.disabled = true;
			document.getElementById('TShostile')
				.disabled = true;
			document.getElementById('TSfriendly')
				.disabled = true;
			document.getElementById('TSfriendlyToUs')
				.disabled = true;
			document.getElementById('TSneutral')
				.disabled = true;
			document.getElementById('DIVmisted')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterMisted + '</font>';
			document.getElementById('DIVhostile')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterHostile + '</font>';
			document.getElementById('DIVfriendly')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterFriendly + '</font>';
			document.getElementById('DIVfriendlyToUs')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterFriendlyToUs + '</font>';
			document.getElementById('DIVneutral')
				.innerHTML = '<FONT color=grey>' + culang.searchFilterNeutral + '</font>';
		}
		document.getElementById('DIVallied')
			.innerHTML = '<FONT color=black>' + culang.searchFilterAllied + '</font>';
		document.getElementById('DIVunAllied')
			.innerHTML = '<FONT color=black>' + culang.searchFilterUnallied + '</font>';
		document.getElementById('DIVmight')
			.innerHTML = '<FONT color=black>' + culang.searchFilterMightInMillion + '</font>';
		document.getElementById('DIVmightMin')
			.innerHTML = '<FONT color=black>' + culang.searchFilterMin + '</font>';
		document.getElementById('DIVmightMax')
			.innerHTML = '<FONT color=black>' + culang.searchFilterMax + '</font>';
		document.getElementById('DIVfilterTop')
			.innerHTML = '<FONT color=black>' + culang.searchFilterAlliancesRank + '</font>';
		document.getElementById('DIVtop')
			.innerHTML = '<FONT color=black>' + culang.searchFilterTo + '</font>';
		document.getElementById('TSallied')
			.disabled = false;
		document.getElementById('TSunAllied')
			.disabled = false;
		document.getElementById('TSmightMin')
			.disabled = false;
		document.getElementById('TSmightMax')
			.disabled = false;
		document.getElementById('TSfilerTop')
			.disabled = false;
		document.getElementById('TStopMin')
			.disabled = false;
		document.getElementById('TStopMax')
			.disabled = false;
	},
	show: function () {
		var t = Tabs.TurboSearch;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pageNo = 1;
		params.cityId = uW.currentcityid;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/allianceGetOtherInfo.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				var data = rslt.otherAlliances;
				for (y = 0; y < data.length; y++) t.rankings[data[y].allianceId] = data[y].ranking;
				var params = uW.Object.clone(uW.g_ajaxparams);
				params.pageNo = 2;
				params.cityId = uW.currentcityid;
				new MyAjaxRequest(uW.g_ajaxpath + "ajax/allianceGetOtherInfo.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					onSuccess: function (rslt) {
						var data = rslt.otherAlliances;
						for (y = 0; y < data.length; y++) t.rankings[data[y].allianceId] = data[y].ranking;
					},
				});
			},
		});
	},
	hide: function () {},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Search.js">
//	
//	   KOC POWER - TABS SEARCH											        
//	


Tabs.Search = {
	tabOrder: TabOptions.toSearch,
	tabLabel: culang.tabLabelSearch,
	cont:null,
	state : null,
	show : function (div){
		var t = Tabs.Search;
	},
	hide : function (){
	},
	clickedPlayerDetail : function (span, uid){
		var t = Tabs.Player;
		span.onclick = '';
		span.innerHTML = ""+culang.searchPlayerDetails+"";
		t.fetchPlayerInfo (uid, function (r) {t.gotPlayerDetail(r, span)});
	},
	clickedPlayerLeaderboard : function (span, uid){
		var t = Tabs.Player;
		span.onclick = '';
		span.innerHTML = "<i><b>"+culang.searchPlayerLeaderboard+"</b></i>";
		t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard(r, span)});
	},
	gotPlayerLeaderboard : function (rslt, span){
		var t = Tabs.Player;
		if (!rslt.ok){
			span.innerHTML = rslt.errorMsg;
			return;
		}
		if (rslt.totalResults == 0){
			span.innerHTML = "<B></b>"+culang.mainError+": "+culang.searchNotFoundInMist+"";
			return;
		}
		var p = rslt.results[0];
		var an = p.allianceName;
		if (!an || an=='' || p.officerType==4)
			an = 'Aucun';
		else
			an += ' ('+ officerId2String(p.officerType) +')';
		m = '<TABLE cellspacing=0 class=pdxTab><TR><TD><B>'+culang.mainCastle+': </b></td><TD colspan=2> '+uW.g_js_strings.commonstr.might+': '+ p.might  +' &nbsp; '+uW.g_js_strings.commonstr.alliance+': '+ an +'</td></tr>';
		for (var i=0; i<p.cities.length; i++){
			var c = p.cities[i];
			m += '<TR><TD align=right><B>'+culang.mainCity+' #'+ (i+1) +':</b></td><TD> &nbsp; '+ c.cityName
				+' <a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ c.xCoord +',' +c.yCoord+ ')</a></td><TD width=75%> &nbsp; '+uW.g_js_strings.commonstr.level+': '
				+ c.tileLevel +' &nbsp; &nbsp; status: '+ cityStatusString (c.cityStatus) +' &nbsp; &nbsp; '+culang.searchPlayerCreate+' ' + c.dateCreated.substr(0,10) +'</td></tr>';
		}
		span.innerHTML = m + '</table>';
	},
	gotPlayerDetail : function (rslt, span){
		var t = Tabs.Player;
		if (!rslt.ok){
			span.innerHTML = rslt.errorMsg;
			return;
		}
		var u = rslt.userInfo[0];
		var a = 'Aucun';
		if (u.allianceName)
			a = u.allianceName +' ('+ getDiplomacy(u.allianceId) + ')';
		var m = '<TABLE cellspacing=0 class=pdxTab><TR><TD><B>'+culang.searchDetails+':</b> &nbsp; </td><TD>'+uW.g_js_strings.commonstr.alliance+': '+ a +' &nbsp; '+culang.mainCities+': '
			+ u.cities +' &nbsp; '+culang.mainPopulation+': '+ u.population +'</td></tr><TR><TD></td><TD>'+culang.mainProvinces+': ';
		var pids = u.provinceIds.split (',');
		var p = [];
		for (var i=0; i<pids.length; i++)
			p.push(uW.provincenames['p'+pids[i]]);
		span.innerHTML = m + p.join (', ') +'</td></tr></table>';
	},

	aName : '',
	eventSubmit : function (){
		var t = Tabs.Player;
		ById('ptallErr').innerHTML='';
		t.aName = ById('allAllName').value;
		if (t.aName.length < 3){
			ById('ptallErr').innerHTML = ''+culang.searchMin3Letter+'';
			return;
		}
		var myA = getMyAlliance ();
		ById('altInput').innerHTML = '';
		ById('allListOut').innerHTML = '<BR><center><b><i>'+culang.searchPlayerLeaderboard+'</i></b></center>';
		if (myA[0]!=0 && myA[1].toLowerCase().indexOf(t.aName.toLowerCase())>=0 )
			t.fetchAllianceList (t.aName, myA[0], t.eventGotAllianceList);
		else
			t.fetchAllianceList (t.aName, null, t.eventGotAllianceList);
	},
	init : function (div){
		var t = Tabs.Search;
		this.cont = div;
		uW.BoPTpd = t.clickedPlayerDetail;
		uW.BoPTpd2 = t.clickedPlayerLeaderboard;
		uW.BoPCpo2 = t.clickedPlayerCheckOnline;
		uW.BoPCplo2 = t.clickedPlayerGetLastLogin;
		var Provinces={1:{name:uW.provincenames["p1"],x:75,y:75},2:{name:uW.provincenames["p2"],x:225,y:75},3:{name:uW.provincenames["p3"],x:375,y:75},4:{name:uW.provincenames["p4"],x:525,y:75},5:{name:uW.provincenames["p5"],x:675,y:75},6:{name:"Paimpont",x:75,y:225},7:{name:"Cameliard",x:225,y:225},8:{name:"Sarras",x:375,y:225},9:{name:"Canoel",x:525,y:225},10:{name:"Avalon",x:675,y:225},11:{name:"Carmathen",x:75,y:375},12:{name:"Shallot",x:225,y:375},13:{name:"-------",x:375,y:375},14:{name:uW.provincenames["p13"],x:525,y:375},15:{name:uW.provincenames["p14"],x:675,y:375},16:{name:uW.provincenames["p15"],x:75,y:525},17:{name:uW.provincenames["p16"],x:225,y:525},18:{name:uW.provincenames["p17"],x:375,y:525},19:{name:uW.provincenames["p18"],x:525,y:525},20:{name:uW.provincenames["p19"],x:675,y:525},21:{name:uW.provincenames["p20"],x:75,y:675},22:{name:uW.provincenames["p21"],x:225,y:675},23:{name:uW.provincenames["p22"],x:375,y:675},24:{name:uW.provincenames["p23"],x:525,y:675},25:{name:uW.provincenames["p24"],x:675,y:675}}
		if (t.state == null){
			this.cont.innerHTML = '\
		<DIV class=pdxEntry><table><tr valign=bottom><TD class=xtab width=100 align=right>'+culang.mainType+': </td><TD>\
		<SELECT id="srcType">\
		<OPTION value=0>'+uW.g_js_strings.commonstr.barbariancamp+'</option>\
		<OPTION value=1>'+uW.g_js_strings.commonstr.wilderness+'</option>\
		<OPTION value=2>'+culang.mainCities+'</option>\
		<OPTION value=3>'+uW.g_js_strings.commonstr.darkForest+'</option>\
		<OPTION value=4>'+uW.g_js_strings.commonstr.mercenaryHideout+'</option>\
		</select></td></tr>\
		</table>\
        <DIV id="srcOpts" style="max-height:80px"></div></div>\
        <DIV id="srcResults" style="max-height:'+(Options.HauteurBoite-80)+'px; overflow:auto;"></div>';
			var psearch = document.getElementById ("pasrcType");
			m = '<TABLE><TR valign=middle><TD class=xtab width=100 align=right>&nbsp; X: </td><TD class=xtab>\
        <INPUT id="srchX" type=text size=3\> &nbsp; Y: <INPUT id="srchY" type=text size=3\>';
			m += '&nbsp;<span><select id="KsprovinceXY"><option>--'+uW.g_js_strings.commonstr.province+'--</option>';
			for (var i in Provinces) {
				m += '<option value="'+i+'">'+Provinces[i].name+'</option>';
			}
			m += '</select></span> &nbsp; <SPAN id=spInXY></span>';
			m += '</td></tr><TR><TD class=xtab align=right>'+culang.mainDistance+': </td><TD class=xtab>'+culang.shortMin+' <INPUT id=srcaDist size=4 value=0 /> '+culang.shortMax+' <INPUT id=srcDist size=4 value=10 /></td></tr>';
			m += '<TR><TD class=xtab></td><TD class=xtab><INPUT id=srcStart type=submit value="'+culang.searchStart+'"/></td></tr>';
			m += '</table>';
			document.getElementById ('srcOpts').innerHTML = m;
			var citysrc0=new CdispCityPicker ('srchdcp', document.getElementById ('spInXY'), false, t.clickCitySourceSelect, Cities.byID[uW.currentcityid].idx);
			if (Options.srcTypeSelect)
				document.getElementById ('srcType').value=Options.srcTypeSelect;
			if (Options.srcaDist)
				document.getElementById ('srcaDist').value=Options.srcaDist;
			if (Options.srcDist)
				document.getElementById ('srcDist').value=Options.srcDist;
			document.getElementById ('srcType').addEventListener ('change', function() {
				Options.srcTypeSelect = document.getElementById ('srcType').value;
				saveOptions();
			}, false);
			document.getElementById ('srcaDist').addEventListener ('change', function() {
				Options.srcaDist = document.getElementById ('srcaDist').value;
				saveOptions();
			}, false);
			document.getElementById ('srcDist').addEventListener ('change', function() {
				Options.srcDist = document.getElementById ('srcDist').value;
				saveOptions();
			}, false);
			document.getElementById ('KsprovinceXY').addEventListener ('change', function() {
				if (this.value >= 1) {
					document.getElementById ('srchX').value = Provinces[this.value].x;
					document.getElementById ('srchY').value = Provinces[this.value].y;
					document.getElementById ('srcDist').value = "75";
				}
			}, false);
			document.getElementById ('srcStart').addEventListener ('click', t.clickedSearch, false);
			t.state = 1;
		}
	},
	clickCitySourceSelect : function (city){
		var t = Tabs.Search;
		t.sourceCity = city;
		document.getElementById ('srchX').value=t.sourceCity.x;
		document.getElementById ('srchY').value=t.sourceCity.y;
	},
	opt : {},
	searchRunning : false,
	tilesSearched : 0,
	tilesFound : 0,
	curX : 0,
	curY : 0,
	lastX : 0,
	firstX : 0,
	firstY : 0,
	lastY : 0,
	normalizeCoord : function (x){
		if ( x >= 750)
			x -= 750;
		else if (x < 0)
			x += 750;
		return parseInt (x/5) * 5;
	},
	clickedSearch : function (){
		var t = Tabs.Search;
		if (t.searchRunning){
			t.stopSearch (''+culang.searchCanceled+'');
			return;
		}
		t.opt.searchType = document.getElementById ('srcType').value;
		t.opt.startX = parseInt(document.getElementById ('srchX').value);
		t.opt.startY = parseInt(document.getElementById ('srchY').value);
		t.opt.maxDistance = parseInt(document.getElementById ('srcDist').value);
		t.opt.maxDistanceA = parseInt(document.getElementById ('srcaDist').value);
		errMsg = '';
		if (isNaN (t.opt.startX) ||t.opt.startX<0 || t.opt.startX>749)
			errMsg = ""+culang.searchXmustBe+"<BR>";
		if (isNaN (t.opt.startY) ||t.opt.startY<0 || t.opt.startY>749)
			errMsg += ""+culang.searchYmustBe+"<BR>";
		if (isNaN (t.opt.maxDistanceA) ||t.opt.maxDistanceA<0)
			errMsg += ""+culang.searchMinGreater0+"<BR>";
		if (isNaN (t.opt.maxDistance) ||t.opt.maxDistance<1)
			errMsg += ""+culang.searchMaxGreater0+"<BR>";
		if (t.opt.maxDistance<=t.opt.maxDistanceA)
			errMsg += ""+culang.searchMaxGreaterMin+"<BR>";
		if(t.opt.maxDistanceA > 375)
			errMsg += ""+culang.searchMax375+"<BR>";
		if (errMsg != ''){
			ById('srcResults').innerHTML = '<FONT COLOR=#660000>'+culang.mainError+':</font> '+ errMsg;
			return;
		}

		t.searchRunning = true;
		document.getElementById ('srcStart').value = ''+culang.searchStop+'';
		m = '<DIV class=pdxStat><TABLE width=100% cellspacing=0><TR><TD class=xtab width=125><DIV id=statSearched></div></td>\
        <TD class=xtab align=center><SPAN id=statStatus></span></td>\
        <TD class=xtab align=right width=125><DIV id=statFound></div></td></tr></table></div>\
      <TABLE width=95%><TR valign=top><TD><DIV id=divOutTab style="max-height:'+(Options.HauteurBoite-230)+'px; overflow:auto; width:500px;"></div></td>\
      <TD id="tddivOutOpts" width=100% height=100% style="background:#e0e0f0; border:1px outset #141516; border-radius:5px;-moz-box-shadow: 2px 2px 2px 2px #141516; -webkit-box-shadow: 2px 2px 2px 2px #141516; box-shadow: 2px 2px 2px 2px #141516; height:100%; padding:5px"><DIV id=divOutOpts></div></td></tr><tr><td colspan=2><div id=KsdivKOCAttackExport style="position:absolute;background-color:white; max-height:470px; overflow-y:auto; width:600px;display:none"></div></td><input type=checkbox id=ShowHideOpts>'+culang.searchShowHideOptions+'</tr></table>';
		ById('srcResults').innerHTML = m;
		//
		ById('ShowHideOpts').addEventListener ('click', function (){
			if (ById("ShowHideOpts").checked) {
				ById("tddivOutOpts").style.display="none";
				ById("divOutTab").style.width="100%";
				ById("divOutTab").style.overflow="none";

			} else {
				ById("tddivOutOpts").style.display="block";
				ById("divOutTab").style.width="500px";
			}
		}, false);

		if (t.opt.searchType == 0)
      typeName = uW.g_js_strings.commonstr.barbarians;
    else if (t.opt.searchType == 1)
      typeName = uW.g_js_strings.commonstr.wilderness;
    else if (t.opt.searchType == 3)
      typeName = uW.g_js_strings.commonstr.darkForest;
		else if (t.opt.searchType == 4)
      typeName = uW.g_js_strings.commonstr.mercenaryHideout;
    else
	  typeName = uW.g_js_strings.commonstr.cities;

		m = '<CENTER><B>'+culang.searchFor+' '+ typeName +'<BR>\
        '+culang.searchStartpoint+' '+ t.opt.startX +','+ t.opt.startY +'  &nbsp; '+culang.mainDistance+': '+ t.opt.maxDistanceA +' '+culang.mainTo+' '+ t.opt.maxDistance +'<BR></center>\
        <DIV class=pdxEntry><TABLE cellspacing=0 width=100%><TR align=center><TD class=xtab colspan=10><B><u>'+culang.searchOptionsHead+'</u></b><BR></td></tr>';
		if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3 || t.opt.searchType == 4) {
			m += '<TR><TD class=xtab align=right>'+culang.searchLevelMin+'</td><TD class=xtab> <INPUT id=filMinLvl size=2 value='+ Options.srcMinLevel +' /></td></tr>\
        <TR><TD class=xtab align=right>'+culang.searchLevelMax+':</td><TD class=xtab> <INPUT id=filMaxLvl size=2 value='+ Options.srcMaxLevel +' /></td></tr>';
		}
		if (t.opt.searchType == 1){
			m += '<TR><TD class=xtab align=right>'+culang.mainType+':</td><TD class=xtab align=right>\
		'+culang.kocForests+'<INPUT id=woodWild type=CHECKBOX'+ (Options.woodWild?' CHECKED':'') +'></td></tr>';
			m += '<TR><TD class=xtab align=right>'+uW.g_js_strings.commonstr.grassland+'/'+uW.g_js_strings.commonstr.lake+'<INPUT  id=foodWild type=CHECKBOX '+ (Options.foodWild?' CHECKED':'') +'></td>\
		<TD class=xtab align=right>'+uW.g_js_strings.commonstr.mountain+'<INPUT id=mtnWild type=CHECKBOX '+ (Options.mtnWild?' CHECKED':'') +'></td></tr>';
			m += '<TR><TD class=xtab align=right>'+uW.g_js_strings.commonstr.plain+'<INPUT id=plnWild type=CHECKBOX '+ (Options.plnWild?' CHECKED':'') +'></td>\
		<TD class=xtab align=right>'+uW.g_js_strings.commonstr.hills+'<INPUT id=hillWild type=CHECKBOX'+ (Options.hillWild?' CHECKED':'') +'></td></tr>';
			m += '<TR><TD class=xtab align=right>'+culang.searchFilter+'</td><TD class=xtab><SELECT style="width: 135px" id=idTSSrchFilter>\
		<OPTION value=0>'+culang.mainAll+'</option>\
		<OPTION value=1>'+culang.searchFreeSel+'</option>\
		<OPTION value=2>'+culang.searchHostile+'</option>\
		<OPTION value=3>'+culang.searchNeutral+'</option>\
		<OPTION value=4>'+culang.searchNoAlliance+'</option>\
		</select></td></tr>';
		}
		if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3  || t.opt.searchType == 4) {
			m+= '<TR><TD class=xtab align=right>'+culang.searchSort+'</td><TD class=xtab><SELECT id=filSortBy>\
			  <OPTION value="level" '+ (Options.srcSortBy=='level'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.level+'</option>\
			  <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+culang.mainDistance+'</option>';
			if (t.opt.searchType == 1) {
				m+= '<OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>'+culang.mainPlayer+'</option>';
				m+= '<OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.alliance+'</option>';
			}
			m+= '</select></td></tr>\
				<TR><TD class=xtab align=right>'+culang.searchCoordsOnly+'</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
				</table></div><BR><SPAN id=srchSizeWarn></span><DIV id=KspbSrcExp></div>';
		} else {

			m+= '<TR><TD class=xtab align=right >'+culang.mainShow+':</td><TD class=xtab align=left ><SELECT style="width: 135px" id=idSrchFilter>\
			<OPTION value=0>'+culang.mainAll+'</option>\
			<OPTION value=1>'+culang.searchHostile+'</option>\
			<OPTION value=2>'+culang.searchInMist+'</option>\
			<OPTION value=3>'+culang.searchAlly+'</option>\
			<OPTION value=4>'+culang.searchFriendly+'</option>\
			<OPTION value=5>'+culang.searchNeutral+'</option>\
			<OPTION value=6>'+culang.searchNoAlliance+'</option>\
			</select></td></tr>';
/*
			m+= '<TR><TD class=xtab align=right>Trier Par :</td><TD class=xtab><SELECT id=filSortBy>\
			<OPTION value="might" '+ (Options.srcSortBy=='might'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.might+'</option>\
			<OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+culang.mainDistance+'</option>\
				  <OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>'+culang.mainPlayer+'</option>\
			<OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.alliance+'</option>\
			</select></td></tr>\
			<tr><TD class=xtab align=right>'+culang.searchMightMin+'</td><TD class=xtab><input size=8 id=filPuissance value="'+Options.filPuissance+'"></td></tr>\
			<tr><TD class=xtab align=right>'+culang.searchMightMax+'</td><TD class=xtab><select id=filPuissanceMax>\
			<option value="500" '+ (Options.filPuissanceMax=='500'?'SELECTED':'')  +'>500</option>\
			<option value="2500" '+ (Options.filPuissanceMax=='2500'?'SELECTED':'')  +'>2 500</option>\
			<option value="10000" '+ (Options.filPuissanceMax=='10000'?'SELECTED':'')  +'>10 000</option>\
			<option value="50000" '+ (Options.filPuissanceMax=='50000'?'SELECTED':'')  +'>50 000</option>\
			<option value="100000" '+ (Options.filPuissanceMax=='100000'?'SELECTED':'')  +'>100 000</option>\
			<option value="500000" '+ (Options.filPuissanceMax=='100000'?'SELECTED':'')  +'>500 000</option>\
			<option value="1000000" '+ (Options.filPuissanceMax=='1000000'?'SELECTED':'')  +'>1 000 000</option>\
			<option value="100000000" '+ (Options.filPuissanceMax=='100000000'?'SELECTED':'')  +'>100 '+culang.mainMillions+'</option>\
			<option value="900000000" '+ (Options.filPuissanceMax=='900000000'?'SELECTED':'')  +'>900 '+culang.mainMillions+'</option>\</select></td></tr>\
			<TR><TD class=xtab align=right>'+culang.searchCoordsOnly+':</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
			</table></div><BR><SPAN id=srchSizeWarn></span><BR><SPAN id=srchSizeWarn></span><DIV id=KspbSrcExp></div>';
*/			
			m+= '<TR><TD class=xtab align=right>Trier Par :</td><TD class=xtab><SELECT id=filSortBy>\
			<OPTION value="might" '+ (Options.srcSortBy=='might'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.might+'</option>\
			<OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+culang.mainDistance+'</option>\
				  <OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>'+culang.mainPlayer+'</option>\
			<OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.alliance+'</option>\
			</select></td></tr>\
			<tr><TD class=xtab align=right>'+culang.searchMightMin+'</td><TD class=xtab><input size=10 id=filPuissance value="'+Options.filPuissance+'"></td></tr>\
			<tr><TD class=xtab align=right>'+culang.searchMightMax+'</td><TD class=xtab><input size=10 id=filPuissanceMax value="'+Options.filPuissanceMax+'"></td></tr>\
			<TR><TD class=xtab align=right>'+culang.searchCoordsOnly+':</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
			</table></div><BR><SPAN id=srchSizeWarn></span><BR><SPAN id=srchSizeWarn></span><DIV id=KspbSrcExp></div>';
	
		}
		ById('divOutOpts').innerHTML = m;
		if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3 || t.opt.searchType == 4) {
			ById('filMinLvl').addEventListener ('change', function (){
				Options.srcMinLevel = ById('filMinLvl').value;
				saveOptions();
				t.dispMapTable ();
			}, false);
			ById('filMaxLvl').addEventListener ('change', function (){
				Options.srcMaxLevel = ById('filMaxLvl').value;
				saveOptions();
				t.dispMapTable ();
			}, false);
		}
		ById('filSortBy').addEventListener ('change', function (){
			Options.srcSortBy = ById('filSortBy').value;
			saveOptions();
			t.dispMapTable ();
		}, false);
		ById('coordsOnly').addEventListener ('change', function (){ t.dispMapTable (); }, false);
		if (t.opt.searchType == 1){
			ById('foodWild').addEventListener ('change', function(){
				Options.foodWild = ById('foodWild').checked;
				saveOptions();
				t.dispMapTable ();
			}, false);
			ById('hillWild').addEventListener ('change', function(){
				Options.hillWild = ById('hillWild').checked;
				saveOptions();
				t.dispMapTable();
			}, false);
			ById('mtnWild').addEventListener ('change', function(){
				Options.mtnWild = ById('mtnWild').checked;
				saveOptions();
				t.dispMapTable();
			}, false);
			ById('plnWild').addEventListener ('change', function(){
				Options.plnWild = ById('plnWild').checked;
				saveOptions();
				t.dispMapTable();
			}, false);
			ById('woodWild').addEventListener ('change', function(){
				Options.woodWild = ById('woodWild').checked;
				saveOptions();
				t.dispMapTable ();
			}, false);

			ById('idTSSrchFilter').addEventListener ('change', function (){
				Options.TSSrchFilter = (ById('idTSSrchFilter').value);
				saveOptions();
				t.dispMapTable ();
			}, false);
			ById('idTSSrchFilter').value = Options.TSSrchFilter;
		}
		if (t.opt.searchType == 2){

			ById('idSrchFilter').addEventListener ('change', function (){
				Options.citySrchFilter = (ById('idSrchFilter').value);
				saveOptions();
				t.dispMapTable ();
			}, false);

			ById('idSrchFilter').value = Options.citySrchFilter;


			ById('filPuissance').addEventListener ('change', function (){
				Options.filPuissance = parseInt(ById('filPuissance').value);
				saveOptions();
				t.dispMapTable ();
			}, false);
			ById('filPuissanceMax').addEventListener ('change', function (){
				Options.filPuissanceMax = parseInt(ById('filPuissanceMax').value);
				saveOptions();
				t.dispMapTable ();
			}, false);

		}

		t.mapDat = [];
		t.firstX =  t.opt.startX - t.opt.maxDistance;
		t.lastX = t.opt.startX + t.opt.maxDistance;
		t.firstY =  t.opt.startY - t.opt.maxDistance;
		t.lastY = t.opt.startY + t.opt.maxDistance;
		t.tilesSearched = 0;
		t.tilesFound = 0;
		t.curX = t.firstX;
		t.curY = t.firstY;
		var xxx = t.normalizeCoord(t.curX);
		var yyy = t.normalizeCoord(t.curY);
		document.getElementById ('statStatus').innerHTML = ''+culang.searchSearching+' '+ xxx +','+ yyy;
		setTimeout (function(){Map.request (xxx, yyy, 20, t.mapCallback)}, MAP_DELAY);
	},

	dispMapTable : function (){
		var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills, uW.g_js_strings.commonstr.mountain, uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, culang.kocBog, uW.g_js_strings.commonstr.darkForest, 'Camelot1',' Camelot2', 'Camelot3',' Camelot4', 'Camelot5','Camelot6','Ruine'];

		var t = Tabs.Search;
		function mySort(a, b){
			if (Options.srcSortBy == 'level'){
				if ((x = a[4] - b[4]) != 0)
					return x;
			}
			if (Options.srcSortBy == 'might'){
				if ((x = b[10] - a[10]) != 0)
					return x;
			}
			if (Options.srcSortBy == 'alli'){

				if (a[11] < b[11]) return -1;
				else if (a[11] == b[11]) return 0;
				else return 1;

			}
			if (Options.srcSortBy == 'play'){

				if (a[9] < b[9]) return -1;
				else if (a[9] == b[9]) return 0;
				else return 1;

			}
			return a[2] - b[2];
		}

		dat = [];
		for (i=0; i<t.mapDat.length; i++){
			lvl = parseInt (t.mapDat[i][4]);
			type = t.mapDat[i][3];
			puissance = t.mapDat[i][10];
			if (t.opt.searchType == 2 && type == 7 ) {

				switch(parseInt (Options.citySrchFilter)) {
					case 0:
						if (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax) {
							dat.push(t.mapDat[i]);
						}
						break;
					case 1:
						if ((t.mapDat[i][12] == ''+culang.kocHostile+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
							dat.push(t.mapDat[i]);
						}
						break;
					case 2:
						if ((t.mapDat[i][5]===true) && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
							dat.push(t.mapDat[i]);
						}
						break;
					case 3:
						if ((t.mapDat[i][12] == ''+culang.kocAllys+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
							dat.push(t.mapDat[i]);
						}
						break;
					case 4:
						if ((t.mapDat[i][12] == ''+culang.kocFriendly+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
							dat.push(t.mapDat[i]);
						}
						break;
					case 5:
						if ((t.mapDat[i][12] == ''+culang.kocNeutral+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
							dat.push(t.mapDat[i]);
						}
						break;
					case 6:
						if ((t.mapDat[i][12] == ''+culang.kocNoAlliance+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
							dat.push(t.mapDat[i]);
						}
						break;
				}


			} else {
				if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel){

					if ((t.opt.searchType==4 || t.opt.searchType==3 && (type == 8 || type == 9 || type == 10 || type == 11 || type == 12 || type == 13 || type == 14 || type == 15)) || t.opt.searchType==0
						|| (Options.woodWild==1 && type == 3)
						|| (Options.hillWild==1 && type ==4)
						|| (Options.mtnWild==1 && type==5)
						|| (Options.plnWild==1 && type == 6)
						|| (Options.foodWild==1 && (type==1 || type==2)))
						if (Options.TSSrchFilter==0 && (t.opt.searchType==4 || t.opt.searchType==3 || t.opt.searchType==0 || t.opt.searchType==1))
							dat.push (t.mapDat[i]);
						else if (Options.TSSrchFilter==1 && t.mapDat[i][5]===false)
							dat.push (t.mapDat[i]);
						else if (Options.TSSrchFilter==2 && t.mapDat[i][12] ==''+culang.kocHostile+'')
							dat.push (t.mapDat[i]);
						else if (Options.TSSrchFilter==3 && t.mapDat[i][12] ==''+culang.kocNeutral+'')
							dat.push (t.mapDat[i]);
						else if (Options.TSSrchFilter==4 && t.mapDat[i][12] ==''+culang.kocNoAlliance+'')
							dat.push (t.mapDat[i]);
				}
			}
		}

		ById('statFound').innerHTML = ''+culang.searchFound+' '+ dat.length;
		if (dat.length == 0){
			m = '<BR><center><b><i>'+culang.searchNoResult+'</i></b></center>';
		} else {
			dat.sort(mySort);
			if (ById("coordsOnly").checked)
				m = '<TABLE align=center id=srcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td></tr>';
			else {
				if (t.opt.searchType == 0 || t.opt.searchType == 3 || t.opt.searchType == 4) {
					m = '<TABLE id=srcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td><TD style="padding-left: 10px">'+culang.shortDistance+'</td><TD style="padding-left: 10px;">'+culang.shortLevel+'</td><TD style="padding-left: 10px;">'+culang.mainType+'</td></tr>';
				}
				if (t.opt.searchType == 1 ) {
					m = '<TABLE id=srcOutTab cellpadding=2 cellspacing=2><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td><TD style="padding-left: 10px">'+culang.shortDistance+'</td><TD style="padding-left: 10px;">'+culang.shortLevel+'</td><TD style="padding-left: 10px;">'+culang.mainType+'</td><TD style="padding-left: 10px;">'+culang.mainPlayer+'</td><td style="padding-left: 10px;">'+culang.mainMight+'</td><td style="padding-left: 10px;">'+uW.g_js_strings.commonstr.alliance+'</td><td>'+culang.mainStatus+'</td><td>'+culang.mainLastLogin+'</td></tr>';
				}
				if (t.opt.searchType == 2) {
					m = '<TABLE id=srcOutTab cellpadding=2 cellspacing=2><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td><TD >'+culang.shortDistance+'</td><TD>'+culang.mainCity+'</td><TD>'+culang.mainPlayer+'</td><TD>'+culang.mainMight+'</td><td>'+uW.g_js_strings.commonstr.alliance+'</td><TD width=80% style="font-size:9px;">'+culang.mainInfo+'</td></tr>';
				}

			}
			var numRows = dat.length;
			if (numRows > 500 && t.searchRunning){
				numRows = 500;
				ById('srchSizeWarn').innerHTML = '<FONT COLOR=#600000>'+culang.mainImportant+': <i>'+culang.searchOnlyShow+' '+ dat.length +' '+culang.searchOnlyShow2+'</i></font>';
			}
			for (i=0; i<numRows; i++){
				m += '<TR valign="top"';
				if (dat[i][12]) m += 'class="'+dat[i][12]+'"';

				if (ById("coordsOnly").checked){
					m += ' ><TD valign="top"><DIV>'+ dat[i][0] +','+ dat[i][1] +'</div></td></tr>';
				} else {
					m += ' ><TD valign="top"><DIV>\
	             <a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ dat[i][0] +','+ dat[i][1] +')</a></div></td>';
					if (t.opt.searchType == 2) {
						m += '<TD align="left"  valign="top"><DIV  onclick="PTscout('+ dat[i][0] +','+ dat[i][1] +');return false;"><img src="'+IMGmarchScouting+'" title="'+culang.mainScout+' !">&nbsp;'+ dat[i][2].toFixed(2) +'</a></td><TD align=left>'+ dat[i][8] +'<br><i>('+dat[i][13]+')</i></td><TD valign="top">'+dat[i][9]+'</td><TD valign="top">'+addCommasInt(dat[i][10])+'</td><td>'+dat[i][11]+'</td><td>';
						if (dat[i][5]) {
							m += '<DIV onclick="BoPTscout('+ dat[i][0] +','+ dat[i][1] +');return false;"><A style="font-size:9px;" >'+culang.mainScouting+'</a></div>';
						} else {
							m += '<DIV onclick="BoPTpd(this, '+ dat[i][7] +')"><A style="font-size:9px;" >'+culang.searchDetails+'</a></div> <DIV style="" onclick="BoPTpd2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainCastle+'</a></div>\
			 		<DIV style="" onclick="BoPCpo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainStatus+'</a></div>\
					<DIV style="" onclick="BoPCplo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainLastLogin+'</a></div>';
							m+= '</td></tr>';
						}
					} else {
						m += '<TD align=right  valign="top">'+ dat[i][2].toFixed(2) +' &nbsp; </td><TD align=right>'+ dat[i][4] +'</td><TD> &nbsp; '+ tileNames[dat[i][3]];
						+'</td>';
						if (t.opt.searchType == 1) {
							if (dat[i][5]) {
								m += '<td>'+dat[i][9]+'<td>'+addCommasInt(dat[i][10])+'</td><td>'+dat[i][11]+'</td>';

								if (dat[i][7] && dat[i][7]!=0) {
									m+='<td><DIV style="" onclick="BoPCpo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainStatus+'</a></div></td><td><DIV style="" onclick="BoPCplo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainLastLogin+'</a></div></td>';
								} else {
									m+='<td>&nbsp;</td><td>&nbsp;</td>';
								}


							} else  {
								m +='<td colspan=5 style="text-align=center"><i><span class="boldGreen">'+culang.searchFree+'</span></i>';
							}
						}else{
							m+="<td></td>";
						}
						m +='</tr>';
					}
				}
			}
			m += '</table>';
		}
		ById('divOutTab').innerHTML = m;
		dat = null;
	},

	mapDat : [],

	stopSearch : function (msg){
		var t = Tabs.Search;
		document.getElementById ('statStatus').innerHTML = '<FONT color=#ffaaaa>'+ msg +'</font>';
		document.getElementById ('srcStart').value = ''+culang.searchStart+'';
		ById('srchSizeWarn').innerHTML = '';
		if (t.opt.searchType==0){
			ById('KspbSrcExp').innerHTML = '<CENTER>'+ strButton20(''+culang.searchExport+'', 'id=KspbSrcDoExp') +'</center>';
			document.getElementById ('KspbSrcDoExp').addEventListener ('click', t.exportKOCattack, false);
		}
		if (t.opt.searchType==3){
			document.getElementById ('KspbSrcExp').innerHTML = '<CENTER>'+ strButton20(''+culang.mainAttack+'', 'id=KsSrcDoFS') +'</center>';
			document.getElementById ('KsSrcDoFS').addEventListener ('click', t.generateFSList, false);
		}
		if (t.opt.searchType==2){
			document.getElementById ('KspbSrcExp').innerHTML = '<CENTER>'+ strButton20(''+culang.searchScoutList+'', 'id=pbSrcDoScout') +'</center>';
			document.getElementById ('pbSrcDoScout').addEventListener ('click', t.generateScoutList, false);
		}
		t.searchRunning = false;
	},
	generateFSList :function () {
		var t = Tabs.Search;
		var bulkFS = [];
		for (i=0; i<t.mapDat.length; i++){
			bulkFS.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2], lvl:parseInt(t.mapDat[i][4])});
		}
		bulkFS = bulkFS.sort(function sort(a,b) {a = parseInt(a['dist']);b = parseInt(b['dist']);return a == b ? 0 : (a < b ? -1 : 1);});
		if(t.selectedCity == null)
			t.selectedCity = Cities.cities[0];
		t.ShowFSList (bulkFS, t.selectedCity);

	},
	ShowFSList:function (coordlist, city) {
		var t = Tabs.Search;
		t.FScity = city;
		if(t.popFS==null){
			t.popFS = new CPopup ('KssrcFS', 0,0, 380,600, true, function (){t.popFS.destroy(); t.popFS=null;});
			t.popFS.centerMe (mainPop.getMainDiv());
			t.popFS.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.searchDarkForestOptions+'</div>';
		}
		var m = '<div>'+uW.g_js_strings.commonstr.level+': <select id=KssrcFSLevel><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select>&nbsp<input type=button id=KssrcFSSave value="'+culang.buttonSave+'"><br>';
		for (r=1; r<16; r++){
			m += '<DIV style="float:left;"><img height=20 title="'+uW.unitcost['unt'+r][0]+'" src=http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+r+'_30.jpg>&nbsp;<input style="border:1px solid black;height:16px;font-size:11px;" id="KsFsUnits'+r+'" type=text size=7 value="0"></DIV>';
		}
		m += '</div><br><br><br><br><br><br><DIV>'+culang.mainCastle+': <span id=KssrcFScitypick> </span></div><BR>';
		m += '<DIV class=pdxStat>'+culang.searchSentScouts+' <span id=KssrcFScity>'+city.name+'</span> '+culang.searchSentScouts2+' <BR> '+culang.mainTargets+': '+coordlist.length+'</div>';
		m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>'+culang.shortCoordinate+'</td><td><select id=pbsrcScout_lvl><option value="">'+uW.g_js_strings.commonstr.level+'</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td>'+culang.shortDistance+'</td></tr>';
		for(i=0; i<coordlist.length; i++){
			m += '<TR style="background-color:white"><TD><input type=checkbox name="pbsrcFSCheck" id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'_'+coordlist[i].lvl+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'_'+coordlist[i].lvl+'" /></td><TD>'+coordlist[i].x+ ','+coordlist[i].y+'</td><td>'+coordlist[i].lvl+'</td><td>'+coordlist[i].dist+'</td></tr>';
		}
		m += '</table></div>';
		m += '<BR><CENTER>'+ strButton20(''+culang.searchStartScout+'', 'id=pbSrcStartScout') +'</center>';
		m += '<CENTER><DIV style="width:100%; max-height:100px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';


		t.popFS.getMainDiv().innerHTML = m;
		new CdispCityPicker ('KsFSPick', ById('KssrcFScitypick'), false, function(c,x,y){ById('KssrcFScity').innerHTML = c.name; t.attackcity = c; }, city.idx);

		t.popFS.show(true);

		ById('KssrcFSSave').addEventListener('click', t.enregistrerscrLevel, false);
		ById('KssrcFSLevel').addEventListener('click', t.changescrLevel, false);
		ById('pbsrcScout_All').addEventListener('change', function(){
			for(k in document.getElementsByName('pbsrcFSCheck'))
				document.getElementsByName('pbsrcFSCheck')[k].checked = ById('pbsrcScout_All').checked;
		}, false);
		ById('pbsrcScout_lvl').addEventListener('change', function(){
			if (ById('pbsrcScout_lvl').value!="") {
				for(k in document.getElementsByName('pbsrcFSCheck')) {
					var lvl = document.getElementsByName('pbsrcFSCheck')[k].value;
					if (lvl!==undefined) {
						var lvll = lvl.split("_");
						if (lvll[2]==ById('pbsrcScout_lvl').value){
							document.getElementsByName('pbsrcFSCheck')[k].checked = true;
						}
					}
				}
			}
		}, false);



		ById('pbSrcStartScout').addEventListener('click', t.clickedStartFSAttack, false);

		t.changescrLevel();
	},
	changescrLevel: function() {
		var t = Tabs.Search;
		if (Options.AttackFSUnits[ById('KssrcFSLevel').value]!==undefined) {
			for (r=1; r<16; r++){
				ById('KsFsUnits'+r).value=Options.AttackFSUnits[ById('KssrcFSLevel').value][r];
			}
		}
	},
	enregistrerscrLevel: function() {
		var t = Tabs.Search;
		Options.AttackFSUnits[ById('KssrcFSLevel').value]=[];
		for (r=1; r<16; r++){
			Options.AttackFSUnits[ById('KssrcFSLevel').value][r] = ById('KsFsUnits'+r).value;
		}
		saveOptions ();
		t.changescrLevel();
	},
	attacking : false,
	attackcity : null,
	doFSAttack: function(list, city){
		var t = Tabs.Search;
		ById('pbSrcScoutResult').innerHTML = '';
		if(list.length < 1){
			ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.searchNoCoords+'</span><br>';
			t.clickedStartFSAttack();
			return;
		}
		for (var lvl=1;lvl<11; lvl++){
			var totalunit=0;
			for (r=1; r<16; r++){
				if (Options.AttackFSUnits[lvl]!=undefined) {
					totalunit += parseInt(Options.AttackFSUnits[lvl][r]);
					if(parseInt(Seed.units['city'+city.id]['unt'+r]) < Options.AttackFSUnits[lvl][r]){
						ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.mainError+': '+uW.unitcost['unt'+r][0]+' '+culang.searchScoutNoAvailable+' '+lvl+'</span><br>';
						t.clickedStartFSAttack();
						return;
					}
				}
			}
		}
		t.doFSAttackCount(list, city, list.length, 0);

	},
	doFSAttackCount : function(list, city, total, count){
		var t = Tabs.Search;

		if(!t.attacking){
			ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.searchStopScout+'</span><BR>';
			ById('pbSrcStartScout').className = 'button20 ptButton20';
			ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStartScout+'</span>';
			return;
		}
		if(total <= (count)){
			ById('pbSrcScoutResult').innerHTML += ''+culang.mainHDone+'<BR>';
			t.clickedStartFSAttack();
			return;
		}
		var rinfo = getRallypointInfo(city.id);
		var rallypointlevel = rinfo.maxMarches;
		var slots = rinfo.usedSlots;
		if(slots >= rallypointlevel){
			setTimeout(function(){t.doFSAttackCount(list, city, total, count)}, 10000);
			ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScoutsWaitForRP+'<br>';
			return;
		}
		var coords = list[count].split("_");
		if(coords[0] == 'undefined' || coords[1] == 'undefined'){
			ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchCoordsInvalid+'</span>';
			t.clickedStartFSAttack();
			return;
		}
		ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScoutsAttacks+' '+coords[0]+','+coords[1]+' '+culang.searchSentScoutsAttacks2+'';
		ById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]+'_'+coords[2]).checked = false;
		t.sendAttackFS(coords[0], coords[1], coords[2], city, count, function(c){t.doFSAttackCount(list, city, total, c)});
	},
	sendAttackFS : function(x, y, lvl, city, count, notify){
		var t = Tabs.Search;
		count = parseInt(count);
		var totalunit = 0;
		for (r=1; r<16; r++) {
			if (Options.AttackFSUnits[lvl]!=undefined)
				totalunit += parseInt(Options.AttackFSUnits[lvl][r]);
		}
		if (totalunit>0) {
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.cid = city.id;
			params.kid = 0;
			params.type = 4;
			params.xcoord = x;
			params.ycoord = y;
			for (r=1; r<16; r++)
				params['u'+r]=parseInt(Options.AttackFSUnits[lvl][r]);
			var knt = new Array();
			for (k in Seed.knights['city' + city.id]){
				if (Seed.knights['city' + city.id][k]["knightStatus"] == 1 && Seed.leaders['city' + city.id]["resourcefulnessKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["politicsKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["combatKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["intelligenceKnightId"] != Seed.knights['city' + city.id][k]["knightId"]){
					knt.push ({
						Name:   Seed.knights['city' + city.id][k]["knightName"],
						Combat:	Seed.knights['city' + city.id][k]["combat"],
						ID:	Seed.knights['city' + city.id][k]["knightId"],
					});
				}
			}
			knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
			if (knt[0]) {
				params.kid= knt[0]["ID"];
				new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					loading: true,
					onSuccess: function (rslt) {
						rslt = eval("(" + rslt.responseText + ")");
						if (rslt.ok) {
							var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
							var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
							var ut = uW.unixtime();
							var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
							for(i = 0; i <= unitsarr.length; i++){
								if(params["u"+i]){
									unitsarr[i] = params["u"+i];
								}
							}
							var resources=new Array();
							resources[0] = params.gold;
							for(i=1; i<=4; i++){
								resources[i] = params["r"+i];
							}
							var currentcityid = params.cid;
							uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
							if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
							ById('pbSrcScoutResult').innerHTML += ''+culang.searchScoutSent+'<BR>';
							if (notify)
								setTimeout(function(){ notify(count+1); }, 1500);
						} else {
							if (rslt.user_action) {
								ById('pbSrcScoutResult').innerHTML += '<span title="'+rslt.msg+'">'+culang.searchScoutCaptcha+'</span><BR>';
							} else {
								if (rslt.error_code==104) {
									rslt.errorMsg = uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));
									ById('pbSrcScoutResult').innerHTML += ' ' + culang.mainError +' - ' + rslt.errorMsg +'<BR>';
									if (notify)
										setTimeout(function(){ notify(count+1); }, 5000);
								} else {
									rslt.errorMsg = uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)).msg;
									ById('pbSrcScoutResult').innerHTML += ' ' + culang.mainError +' - ' + rslt.errorMsg +'<BR>';
									if (notify)
										setTimeout(function(){ notify(count); }, 5000);
								}
							}
						}
					},
					onFailure: function () {}
				});

			} else {
				ById('pbSrcScoutResult').innerHTML += ''+culang.searchScoutKnightError+'<BR>';
				if (notify)
					setTimeout(function(){ notify(count); }, 1000);
			}

		} else {

			ById('pbSrcScoutResult').innerHTML += '<span>'+culang.searchScoutNoParameterError+'</span><BR>';
			setTimeout(function(){ notify(count+1); }, 500);

		}


	},
	generateScoutList : function (){
		var t = Tabs.Search;
		var bulkScout = [];
		for (i=0; i<t.mapDat.length; i++){

			if (t.mapDat[i][3] == 7){

				if(t.mapDat[i][10] >= Options.filPuissance || t.mapDat[i][5]){
					if((Options.citySrchFilter=='1' && t.mapDat[i][12] == ''+culang.kocHostile+'') ||
						(Options.citySrchFilter=='2' && t.mapDat[i][5]===true) ||
						(Options.citySrchFilter=='3' && t.mapDat[i][12] == ''+culang.kocAllys+'') ||
						(Options.citySrchFilter=='4' && t.mapDat[i][12]  == ''+culang.kocFriendly+'') ||
						(Options.citySrchFilter=='5' && t.mapDat[i][12] == ''+culang.kocNeutral+'') ||
						(Options.citySrchFilter=='6' && t.mapDat[i][12] == ''+culang.kocNoAlliance+'') ||
						(Options.citySrchFilter=='0'))
						bulkScout.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2]});
				}
			}
		}
		if(t.selectedCity == null)
			t.selectedCity = Cities.cities[0];
		t.ShowScoutList (bulkScout, t.selectedCity);
	},
	ShowScoutList : function (coordlist, city){
		var t = Tabs.Search;
		var popScout = null;
		t.scoutcity = city;

		if(popScout==null){
			popScout = new CPopup ('pbsrcscout', 0,0, 350,500, true, function (){popScout.destroy(); popScout=null;});
			popScout.centerMe (mainPop.getMainDiv());
		}
		var m = '<DIV>'+culang.searchScoutAmount+' <input id=pbsrcScoutAmt value="'+Options.srcScoutAmt+'" /></div><BR>';
		m += '<DIV>'+culang.mainCastle+': <span id=pbsrcScoutcitypick> </span></div><BR>';
		m += '<DIV class=pdxStat>'+culang.searchSentScouts+' <span id=pbsrcScoutcity>'+city.name+'</span> '+culang.searchSentScouts2+' <BR> '+culang.mainTargets+': '+coordlist.length+'</div>';
		m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>'+culang.searchScoutTargetCoords+'</td></tr>';
		for(i=0; i<coordlist.length; i++){
			m += '<TR style="background-color:white"><TD><input type=checkbox name=pbsrcScoutCheck id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'" /></td><TD>'+coordlist[i].x+','+coordlist[i].y+'</td></tr>';
		}
		m += '</table></div>';
		m += '<BR><CENTER>'+ strButton20(''+culang.searchScoutsStart+'', 'id=pbSrcStartScout') +'</center>';
		m += '<CENTER><DIV style="width:70%; max-height:75px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';
		popScout.getMainDiv().innerHTML = m;
		new CdispCityPicker ('pbScoutPick', ById('pbsrcScoutcitypick'), false, function(c,x,y){ById('pbsrcScoutcity').innerHTML = c.name; t.scoutcity = c; }, city.idx);
		popScout.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.searchScoutsHead+'</div>';
		popScout.show(true);

		ById('pbsrcScoutAmt').addEventListener('change', function(){
			Options.srcScoutAmt = parseInt(ById('pbsrcScoutAmt').value);
			saveOptions();
		}, false);
		ById('pbsrcScout_All').addEventListener('change', function(){
			for(k in document.getElementsByName('pbsrcScoutCheck'))
				document.getElementsByName('pbsrcScoutCheck')[k].checked = ById('pbsrcScout_All').checked;
		}, false);
		ById('pbSrcStartScout').addEventListener('click', t.clickedStartScout, false);
	},
	scouting : false,
	scoutcity : null,
	doScout : function(list, city){
		var t = Tabs.Search;
		ById('pbSrcScoutResult').innerHTML = '';
		if(list.length < 1){
			ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchNoCoords+'</span>';
			t.clickedStartScout();
			return;
		}
		if(parseInt(Seed.units['city'+city.id]['unt'+3]) < Options.srcScoutAmt){
			ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchNoScouts+'</span>';
			t.clickedStartScout();
			return;
		}
		t.doScoutCount(list, city, list.length, 0);

	},
	clickedStartScout : function(){
		var t = Tabs.Search;
		if(t.scouting == false){
			t.scouting = true;
			var ScoutList = [];
			for(k=0; k<document.getElementsByName('pbsrcScoutCheck').length; k++){
				if(document.getElementsByName('pbsrcScoutCheck')[k].checked){
					ScoutList.push(document.getElementsByName('pbsrcScoutCheck')[k].value);
				}
			}
			t.doScout(ScoutList, t.scoutcity);
			ById('pbSrcStartScout').className = 'button20 pbButCancel';
			ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStop+'</span>';
		} else {
			t.scouting = false;
			ById('pbSrcStartScout').className = 'button20 ptButton20';
			ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchScoutsStart+'</span>';
		}
	},
	doScoutCount : function(list, city, total, count){
		var t = Tabs.Search;
		if(!t.scouting){
			ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.searchStop+'</span><BR>';
			ById('pbSrcStartScout').className = 'button20 ptButton20';
			ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchScoutsStart+'</span>';
			return;
		}
		if(total <= (count)){
			ById('pbSrcScoutResult').innerHTML += ''+culang.mainHDone+'<BR>';
			t.clickedStartScout();
			return;
		}
		var rinfo = getRallypointInfo(city.id);
		var rallypointlevel = rinfo.maxMarches;
		var slots = rinfo.usedSlots;
		if(slots >= rallypointlevel){
			setTimeout(function(){t.doScoutCount(list, city, total, count)}, 10000);
			ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScoutsWaitForRP+'<br>';
			return;
		}
		var coords = list[count].split("_");
		if(coords[0] == 'undefined' || coords[1] == 'undefined'){
			ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchCoordsInvalid+'</span>';
			t.clickedStartScout();
			return;
		}
		ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScouts+' '+coords[0]+','+coords[1]+' '+culang.searchSentScouts2+'';
		ById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]).checked = false;
		t.sendScout(coords[0], coords[1], city, count, function(c){t.doScoutCount(list, city, total, c)});
	},
	sendScout : function(x, y, city, count, notify){
		var t = Tabs.Search;
		count = parseInt(count);
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid = city.id;
		params.kid = 0;
		params.type = 3;
		params.xcoord = x;
		params.ycoord = y;
		params.u3 = Options.srcScoutAmt;
		new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				rslt = eval("(" + rslt.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
          var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
							unitsarr[i] = params["u"+i];
						}
					}
					var resources=new Array();
					resources[0] = params.gold;
					for(i=1; i<=4; i++){
						resources[i] = params["r"+i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
					ById('pbSrcScoutResult').innerHTML += ' '+culang.searchScoutSent+'<BR>';
					if (notify)
						setTimeout(function(){ notify(count+1); }, 1000);
				} else if (rslt.error_code==208) {
					rslt.errorMsg = uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));
					ById('pbSrcScoutResult').innerHTML += ' '+culang.searchFailedAttempt+' - ' + rslt.errorMsg + '<BR>';
					if (notify)
						setTimeout(function(){ notify(count+1); }, 1000);
				} else {
					rslt.errorMsg = uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)).msg;
					ById('pbSrcScoutResult').innerHTML += ' '+culang.searchFailedAttempt+' - ' + rslt.errorMsg + '<BR>';
					if (notify)
						setTimeout(function(){ notify(count); }, 1000);
				}
			},
			onFailure: function () {}
		});
	},
	getRallypoint: function(cityId){
		var t = Tabs.Search;
		cityId = 'city'+cityId;
		for (o in Seed.buildings[cityId]){
			var buildingType = parseInt(Seed.buildings[cityId][o][0]);
			var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
			if (buildingType == 12){
				return parseInt(buildingLevel);
				break;
			}
		}
		return 0;
	},
	clickedStartFSAttack : function(){
		var t = Tabs.Search;
		if(t.attacking == false){
			t.attacking = true;
			var ScoutList = [];
			for(k=0; k<document.getElementsByName('pbsrcFSCheck').length; k++){
				if(document.getElementsByName('pbsrcFSCheck')[k].checked){
					ScoutList.push(document.getElementsByName('pbsrcFSCheck')[k].value);
				}
			}
			t.doFSAttack(ScoutList, t.attackcity);
			ById('pbSrcStartScout').className = 'button20 pbButCancel';
			ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStopScout+'</span>';
		} else {
			t.attacking = false;
			ById('pbSrcStartScout').className = 'button20 ptButton20';
			ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStartScout+'</span>';
		}
	},
	clickedPlayerCheckOnline : function (span, uid){
		var t = Tabs.Player;
		var s = Tabs.Search;
		span.onclick = '';
		span.innerHTML = ""+culang.searchPlayerCheckOnline+"";
		t.fetchPlayerStatusSimple (uid, function (r) {s.gotPlayerStatus(r, span, uid)});
	},

	clickedPlayerGetLastLogin : function (span, uid){
		var t = Tabs.Player;
		var s = Tabs.Search;
		span.onclick = '';
		span.innerHTML = ""+culang.searchLastLogin+"";
		t.fetchPlayerLastLogin (uid, function (r) {s.gotPlayerLastLogin(r, span)});
	},
	gotPlayerStatus : function (rslt, span,uid){
		var t = Tabs.Player;
		if (!rslt.ok){
			span.innerHTML = rslt.errorMsg;
			return;
		}

		var p = rslt.data;
		if (p[uid] == true) {
			m = '<span style="color:green"><b>'+culang.movementPlayerCheckOn+'</b></span>';
		} else {
			m = '<span style="color:red"><b>'+culang.movementPlayerCheckOff+'</b></span>';
		}
		span.innerHTML = m + '';
	},

	gotPlayerLastLogin : function (rslt, span){
		var t = Tabs.Player;
		if (!rslt.ok){
			span.innerHTML = rslt.errorMsg;
			return;
		}

		var p = rslt.playerInfo;
		var lastLogin = rslt.playerInfo.lastLogin;

		if (lastLogin) {
			m = '<span style="color:black">'+lastLogin+'</span>';
		} else {
			m = '<span style="color:red">?</span>';
		}
		span.innerHTML = m + '';
	},
	exportKOCattack : function (){
		var t = Tabs.Search;
		var bulkAdds = {};
		for (i=1; i<11; i++)
			bulkAdds['lvl'+ i] = [];
		for (i=0; i<t.mapDat.length; i++){
			var lvl = parseInt (t.mapDat[i][4]);
			if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel && t.mapDat[i][3]==0)
				bulkAdds['lvl'+ lvl].push({x:t.mapDat[i][0], y:t.mapDat[i][1]});
		}
		exportToKOCattackKs.doExport (bulkAdds, t.selectedCity);
	},
	mapCallback : function (left, top, width, rslt){
		function insertRow (x, y, msg){
			row = ById('srcOutTab').insertRow(-1);
			row.insertCell(0).innerHTML = x +','+ y;
			row.insertCell(1).innerHTML = distance (t.opt.startX, t.opt.startY, x, y);
			row.insertCell(2).innerHTML = msg;
		}
		var t = Tabs.Search;
		if (!t.searchRunning)
			return;
		if (!rslt.ok){
			t.stopSearch (''+culang.mainError+': '+ rslt.errorMsg);
			return;
		}
		if (rslt.error_code == 9) {
			document.getElementById ('statStatus').innerHTML = 'MAP-Error (60sec): '+ left +','+ top;
			setTimeout (function(){
				document.getElementById ('statStatus').innerHTML = ''+culang.searchSearching+' '+ left +','+ top;
				Map.request (left, top, 20, t.mapCallback);
			}, 61000);
			return;
		}
		map = rslt.data;
		var userInfo = rslt.userInfo;
		var alliance = rslt.allianceNames;
		for (k in map){
			if (t.opt.searchType==0 && map[k].tileType==51 && !map[k].tileCityId ) {
				type = 0;
			} else if (t.opt.searchType==1 && map[k].tileType>=10 &&  map[k].tileType<=50) {
				if (map[k].tileType == 10)
					type = 1;
				else if (map[k].tileType == 11)
					type = 2;
				else
					type = (map[k].tileType/10) + 1;
			} else if (t.opt.searchType==2 && map[k].tileCityId >= 0 && map[k].tileType > 50 && map[k].cityName) {
				type = 7;
			} else if (t.opt.searchType==3 && map[k].tileType==54) {
        type=9;
      } else if (t.opt.searchType==4 && map[k].tileType==55) {
				type=10;
      } else if (t.opt.searchType==3 && map[k].tileType>100) {
        type= 9 + (map[k].tileType-100);
      } else {
        continue;
      }
			dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
			if (dist <= t.opt.maxDistance && dist >= t.opt.maxDistanceA){
				if (t.opt.searchType==2) {
					var isMisted = map[k].tileUserId == 0 || false;
					var uu = 'u'+map[k].tileUserId;
					var aU = ''+culang.mainUnknown+'';
					var aD = ''+culang.mainUnknown+'';
					var mightU = 0;
					var nameU = ''+culang.mainUnknown+'';
					if (isMisted) {
						nameU = ''+culang.mainInFog+'';
						mightU = 0;
					} else {
						if (userInfo[uu] ) {
							nameU = "<a onclick=getInfoForAnUser('"+ map[k].tileUserId +"');>"+ userInfo[uu].n +"</a>";
							mightU = userInfo[uu].m;
							aD = getDiplomacy(userInfo[uu].a);
							if ( alliance && alliance['a'+userInfo[uu].a] ) {
								aU = alliance['a'+userInfo[uu].a];
							}
							else {
								aU = '----';
								aD = ''+culang.kocNoAlliance+'';
							}
						}
					}
					// PRestige
					var Prestige="Normal";
					if ( map[k].isPrestige) {
						if (map[k].prestigeType==1) Prestige="Druid " + map[k].prestigeLevel;
						if (map[k].prestigeType==2) Prestige="Fey " + map[k].prestigeLevel;
						if (map[k].prestigeType==3) Prestige="Briton " +map[k].prestigeLevel;
					}
					t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isMisted, map[k].tileCityId, map[k].tileUserId, map[k].cityName,nameU,mightU,aU,aD,Prestige,map[k].tileId]);
					
					//t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isMisted, map[k].tileCityId, map[k].tileUserId, map[k].cityName,nameU,mightU,aU,aD ]);
				} else {
					isOwned = map[k].tileUserId>0 || map[k].misted;
					var uu = 'u'+map[k].tileUserId;
					var aU = ''+culang.mainUnknown+'';
					var aD = ''+culang.mainUnknown+'';
					var nameU = ''+culang.mainUnknown+'';
					var mightU = 0;
					if (map[k].misted) {
						nameU = ''+culang.mainInFog+'';
					}else {
						if (userInfo[uu] ) {
							var nameU = "<a onclick=getInfoForAnUser('"+ map[k].tileUserId +"');>"+ userInfo[uu].n +"</a>";
							mightU = userInfo[uu].m;
							aD = getDiplomacy(userInfo[uu].a);
							if ( alliance && alliance['a'+userInfo[uu].a] ) {
								aU = alliance['a'+userInfo[uu].a];
							}
						}else {
							var nameU = ''+culang.mainUnknown+'';
						}
					}
					t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isOwned, map[k].tileCityId, map[k].tileUserId, map[k].cityName, nameU, mightU, aU, aD,0,map[k].tileId]);
					//t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isOwned, map[k].tileCityId, map[k].tileUserId, map[k].cityName, nameU, mightU, aU, aD]);
				}
				++t.tilesFound;
			}
		}
		t.tilesSearched += (20*20);
		ById('statSearched').innerHTML = ''+culang.searchSearched+' '+ t.tilesSearched;
		t.dispMapTable();
		t.curX += 20;
		if (t.curX > t.lastX){
			t.curX = t.firstX;
			t.curY += 20;
			if (t.curY > t.lastY){
				t.stopSearch (''+culang.mainHDone+'');
				return;
			}
		}
		var x = t.normalizeCoord(t.curX);
		var y = t.normalizeCoord(t.curY);
		document.getElementById ('statStatus').innerHTML = ''+culang.searchSearching+' '+ x +','+ y;
		setTimeout (function(){Map.request (x, y, 20, t.mapCallback)}, MAP_DELAY);
	},
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/ThroneStuff.js">
//	
//	   KOC POWER - TABS THRONESTUFF									        
//	
/*
function getSpeedup(time) {
		var item = 0;
		if (time >= 280800 && parseInt(Seed.items.i10) > 0 && Options.speed10) item = 10; //4tage
		else if (time >= 151200 && time < 280800 && parseInt(Seed.items.i8) > 0 && Options.speed8) item = 8; //2,5 Tage
		else if (time >= 70200 && time < 151200 && parseInt(Seed.items.i7) > 0 && Options.speed7) item = 7; //24 Stunden
		else if (time >= 41400 && time < 70200 && parseInt(Seed.items.i6) > 0 && Options.speed6) item = 6; //15 Stunden
		else if (time >= 18900 && time < 41400 && parseInt(Seed.items.i5) > 0 && Options.speed5) item = 5; //8 Stunden
		else if (time >= 6300 && time < 18900 && parseInt(Seed.items.i4) > 0 && Options.speed4) item = 4; //2,5 Stunden
		else if (time >= 2250 && time < 6300 && parseInt(Seed.items.i3) > 0 && Options.speed3) item = 3; //1 Stunde
		else if (time >= 450 && time < 2250 && parseInt(Seed.items.i2) > 0 && Options.speed2) item = 2; //15 Minuten
		else if (time < 450 && time > 15 && parseInt(Seed.items.i1) > 0 && Options.speed1) item = 1; //1 Minute
		return item;
}
*/
function getSpeedup(time) {
		var item = 0;
		//Startitem ermitteln
		if (time >= 280800 && Options.speed10) item = 10; //4tage
		else if (time >= 151200 && time < 280800 && Options.speed8) item = 8; //2,5 Tage
		else if (time >= 70200 && time < 151200 && Options.speed7) item = 7; //24 Stunden
		else if (time >= 41400 && time < 70200 && Options.speed6) item = 6; //15 Stunden
		else if (time >= 18900 && time < 41400 && Options.speed5) item = 5; //8 Stunden
		else if (time >= 6300 && time < 18900 && Options.speed4) item = 4; //2,5 Stunden
		else if (time >= 2250 && time < 6300 && Options.speed3) item = 3; //1 Stunde
		else if (time >= 450 && time < 2250 && Options.speed2) item = 2; //15 Minuten
		else if (time < 450 && time > 15 && Options.speed1) item = 1; //1 Minute
		else return 0;
	
		do {
			if (Options["speed"+item]) {
				if (parseIntNan(Seed.items['i'+item]) <= 0) {
					item--;
				} else {
					break;
				}
			} else {
				item--;
			}
			if (item == 9) item--;
		} while (item > 0);
		return item;	
}



Tabs.ThroneStuff = {
	tabOrder : TabOptions.toThroneStuff,
	tabLabel : culang.tabLabelThroneStuff,
	cont : null,
	curTabBut : null,
	curTabName : null,
	SelId:null,
	log:[],
	SalvageLog:[],
	SalvagePreviewList:[],
	timersalvage:null,
	setRepairTimer:null,
	setActionTimer:null,
	SalvageArray:[],
	SalvageArrayP1:[],
	SalvageRunning:false,
	LastDeleted:0,
	viewstats:null,
	viewUniqueItems:null,
	EquipType: ["Advisor","Banner","Chair","Table","Windows","Trophy", "Candelabrum","Hero"],
	actDelItem:0,
	timer: null,

	init : function (div){
		var t = Tabs.ThroneStuff;
		t.cont = div;

		var a = JSON2.parse(GM_getValue ('ThroneHistory_'+getServerId(), '[]'));
		if (matTypeof(a) == 'array') t.log = a;
		var a = JSON2.parse(GM_getValue ('ThroneSalvageHistory_'+getServerId(), '[]'));
		if (matTypeof(a) == 'array') t.SalvageLog = a;

		ThroneDelItems = ById('pbsalvage_run');
		if (Options.ThroneDeleteItems == false) {
			if (ThroneDelItems) ThroneDelItems.value = culang.throneStuffAutoSalvage+" = "+culang.buttonOFF;
		} else {
			if (ThroneDelItems) ThroneDelItems.value = culang.throneStuffAutoSalvage+" = "+culang.buttonON;
			t.timersalvage=setTimeout(t.salvageCheck,60000);
		}
		if (ThroneOptions.delItem > 0 ) t.doSalvageNew();
		var main = '<TABLE align=center><TR><TD><INPUT class=ksSubtab ID=ptmrchSubSal type=submit value="'+culang.throneStuffSalvage+'"></td>';
		main +='<TD><INPUT class=ksSubtab ID=ptmrchSubUE type=submit value="'+culang.throneStuffUpgradeEnhance+'"></td><TD><INPUT class=ksSubtab ID=ptmrchSubRE type=submit value="'+culang.throneStuffRepair+'"></td>';
		main +='<TD><INPUT class=ksSubtab ID=ptmrchSubST type=submit value="'+culang.throneStuffStats+'"></td><TD><INPUT class=ksSubtab ID=ptmrchSubEQ type=submit value="'+culang.throneStuffEquip+'"></td>';
		main +='<td><INPUT class=ksSubtab ID=ptThroneChance type=submit value="'+culang.throneChance+'"></td>';
		main +='<td><INPUT class=ksSubtab ID=ptUniqueItems type=submit value="'+culang.UniqeItems+'"></td>';
		main +='<td><INPUT class=ksSubtab ID=ptThroneCaps type=submit value="'+culang.infoHeadThroneCaps+'"></td>';
		main +='</tr></table>';
		main +='<DIV id=ThroneOutput style="max-height:'+(Options.HauteurBoite-130)+'px; overflow-y:auto"></div>';

		t.cont.innerHTML = main;
		t.Overv = document.getElementById('ThroneOutput');

		document.getElementById('ptmrchSubSal').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubUE').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubST').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubEQ').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptmrchSubRE').addEventListener('click', e_butSubtab, false);
		document.getElementById('ptThroneChance').addEventListener('click', t.throneChance, false);
		document.getElementById('ptUniqueItems').addEventListener('click', t.UniqueItems, false);
		document.getElementById('ptThroneCaps').addEventListener('click', t.ThroneCaps, false);
		changeSubtab (document.getElementById('ptmrchSubUE'));

		function e_butSubtab (evt){
			changeSubtab (evt.target);
		}

		function changeSubtab (but){
			if (but == t.curTabBut)
				return;
			if (t.curTabBut){
				t.curTabBut.className='ksSubtab';
				t.curTabBut.disabled=false;
			}
			t.curTabBut = but;
			but.className='ksSubtab ksSubtabSel';
			but.disabled=true;
			t.curTabName = but.id.substr(9);
			Options.curMarchTab = t.curTabName;
			t.show ();
		}
		t.checkUpgradeInfo(true);
		if (ThroneOptions.Active) t.setActionTimer = setInterval(t.doAction,10000);

	},
	
	UseSpeedup: function() {
		var t = Tabs.ThroneStuff;
		clearTimeout(t.timer);
		try {
		var now = unixTime();
		//RefreshSeed aktiv?
		if (RefreshingSeed) {
			t.timer = setTimeout(t.UseSpeedup, 2000);
			return;
		}
				
		//Sollten Stundenglaeser verwendet werden?
		if (Options.throneUseSpeedups == false) {
			return;
		}
		
		//Wird gerade Repariert?
		var time = 0;
		if (Seed.queue_throne.itemId) {
			time = parseIntNan(Seed.queue_throne.end - now);
		}	else {
			t.timer = setTimeout(t.UseSpeedup, 5000);
			return;
		}
		
		//Passende Sanduhr ermitteln
		var item = getSpeedup(time);

		//Keine passende Sanduhr
		if (item == 0) {
			t.timer = setTimeout(t.UseSpeedup, 5000);
			return;
		}	
		//Speedup verwenden
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = "throneRoom\\ThroneRoomServiceAjax";
		params.action = "speedupRepair";
		params.throneItemId = Seed.queue_throne.itemId;
		params.speedupItemId = item;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					//Item aus Inventar entfernen
					Seed.items["i" + item] = parseInt(Seed.items["i" + item]) - 1;
					uW.ksoItems[item].subtract();
										
					//Zeit um Itemzeit reduzieren
					var timered = 0;
					var timeredarr = [60, 900, 3600, 9000, 28800, 54000, 86400, 216000, 0, 345600];			
					var utstart = parseInt(Seed.queue_throne.start);
					var uteta = parseInt(Seed.queue_throne.end);
					timered = timeredarr[parseInt(item) - 1];
					Seed.queue_throne.start = utstart - timered;
					Seed.queue_throne.end = uteta - timered;
					uW.cm.ThronePanelView.appliedSpeedUp();

					//Logbucheintrag
					var rep = {
						'item' : uW.itemlist['i'+item].name,
					};
					actionLog(culang.tabLabelThroneStuff,culang.throneStuffUseSpeedupsOK.mreplace(rep));		
				} else {
					//Logbucheintrag
					var rep = {
						'item' : uW.itemlist['i'+item].name,
					};
					actionLog(culang.tabLabelThroneStuff,culang.throneStuffUseSpeedupsFail.mreplace(rep) + ' <span class="boldRed">('+rslt.error_code+') ' + rsltErrorCode(rslt) + '</span>');	
				}
			},
		});
		
		} catch (ex) {
			alert('9970/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
		t.timer = setTimeout(t.UseSpeedup, 5000);
	},
	
	ThroneCaps: function() {
		var t = Tabs.ThroneStuff;
		if(t.viewThronecaps == null)
			t.viewThronecaps = new CPopup ('pbviewThroneCaps', 0, 0, 400, 700, true);
		t.viewThronecaps.centerMe (mainPop.getMainDiv());
		m = '<div style="max-height:600; height:600px;overflow-y:auto;">';
		m += '<table border="1" cellpadding="2"><tr><td><b>Boostname</b></td><td><b>Max</b></td><td><b>Min</b></td><td><b>CapType</b></td></tr>';
		for (b in uW.cm.thronestats.boosts) {
			var bo = uW.cm.thronestats.boosts[b];
			m += '<tr><td>'+bo['BoostName']+'</td>'; 
			m += '<td>'+bo['Max']+'</td>'; 
			m += '<td>'+bo['Min']+'</td>'; 
			m += '<td>'+bo['CapType']+'</td></tr>'; 
		}
		m += '</table></div>';
		
		t.viewThronecaps.getMainDiv().innerHTML = m;
		t.viewThronecaps.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.infoHeadThroneCaps+'</div>';
		t.viewThronecaps.show(true);
	},
	

	UniqueItems: function() {
		var t = Tabs.ThroneStuff;
try {
		if(t.viewUniqueItems == null)
			t.viewUniqueItems = new CPopup ('pbviewUniqueItems', 0, 0, 1100, 900, true);
		t.viewUniqueItems.centerMe (mainPop.getMainDiv());
		//Grundwerte
		var unique = uW.cm.WorldSettings.getSettingAsObject("TR_UNIQUE_ITEMS");
		var items_faction = ["","druid","fey","briton"];
		var items_type = ["","chair", "advisor", "window", "banner",  "table", "trophy", "candelabrum",  "hero" ];
		var uniqueInThrone = [];
		for(i in uW.kocThroneItems) {
			var item = uW.kocThroneItems[i];
			if (item.unique > 0) uniqueInThrone.push(item.unique);
		}
		
		var m= '';
		m += '<div style="max-height:800px; height:800px; overflow-y:auto">';
		m += '<TABLE width=100%>';
		for (var i in unique) {
			var item = unique[i];
			if (parseInt(i) > 30000) {
				if (uniqueInThrone.contains(item.Id)) var color = "#ffc"; else var color = "";
				//Kopf
				m += "<tr>";
				m += '<td colspan=2 style="background-color:'+color+'">';
				m += '#'+item.Id + ' ';
				m += '<span class="boldRed">'+uW.g_js_strings.throneRoom['unique_'+items_type[item.Type]+item.Id]+'</span></td>';	
				for (var j = 1; j < 15; j++) {
					m += '<td style="text-align:center;width: 50px;background-color:'+color+'"><b>+'+j+'</b></td>';
				}				
				m += "</tr>";
				//Details
				m += "<tr>";
				m += '<td style="background-color:'+color+'"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/'+item.Id+'.jpg"><br>';	
				m += '<nobr>'+uW.g_js_strings.commonstr.faction+': <b>'+items_faction[item.Faction].capitalize()+'</b></nobr><br>';	
				m += '<nobr>'+uW.g_js_strings.commonstr.type+': <b>'+uW.g_js_strings.throneRoom[items_type[item.Type]]+'</b></nobr></td>';	
				var itemeffects = eval(item.Effects);
				m += '<td style="background-color:'+color+'">';
				for (var e = 0; e<itemeffects.length; e++) {
					var effect = itemeffects[e].type;
					var tier = itemeffects[e].tier;
					m+= '<b><nobr>'+uW.g_js_strings.throneRoom["effectName_"+effect] + '</nobr></b><br>';
				}
				m += '</td>';	
				//Effekte ausrechnen
				for (var j = 1; j < 15; j++) {
					m += '<td style="text-align:center;background-color:'+color+'">';
					for (var e = 0; e<itemeffects.length; e++) {
						var id = itemeffects[e].type;
						var tier = itemeffects[e].tier;
						var level = j;
						p = false;
						while (!p && (tier > -1)) {
							p = uW.cm.thronestats.tiers[id][tier];
							tier--;
						}
						if (p) {
							var base = p.base || 0;
							var growth = p.growth ||0;
							Current = base + ((level * level + level) * growth * 0.5);
							m += Math.round(Current*100)/100 + '%<br>';
						} else m += '?%<br>';
						
					}
					m += '</td>';
				}	
				m += "</tr>";
				m += "<tr>";
				m += '<td colspan=16 style="background-color:white">&nbsp;</td>';
				m += '</tr>';	
			}
		}
		m += '</table>';
		m += '</div>';
		
		t.viewUniqueItems.getMainDiv().innerHTML = m;
		t.viewUniqueItems.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.UniqeItems+'</div>';
		t.viewUniqueItems.show(true);
} catch (ex) {

					alert('9926/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
}				
	},
	
	
	throneChance: function() {
		var t = Tabs.ThroneStuff;
		
		function calc(ue, item, level, H) {
			var C = {
				"0": 0,
				"1VL": 0.005,
				"2VL": 0.0175,
				"3VL": 0.035,
				"4VL": 0.0575,
				"5VL": 0.085,
				"1L": 0.1175,
				"2L": 0.155,
				"3L": 0.1975,
				"1ML": 0.245,
				"2ML": 0.2975,
				"3ML": 0.355,
				"1M": 0.4175,
				"2M": 0.485,
				"3M": 0.5575,
				"1MH": 0.635,
				"2MH": 0.7175,
				"1H": 0.805,
				"2H": 0.8975,
				"1EH": 0.9725,
				"2EH": 1
			};
			var z = C[uW.cm.thronestats[ue][level]["Base"]];	
			var A = 1;
			if (uW.cm.WorldSettings.getSettingAsObject("TR_BUFF_ITEM_MODIFIERS")[H]) {
				A = +uW.cm.WorldSettings.getSettingAsObject("TR_BUFF_ITEM_MODIFIERS")[H]["Chance"] || 1;
			}
			var y = 0;
			if (H && H > 0) {
				y += A - 1;
			}
			y += uW.cm.HeatUpModel.getModifierPercentage() + Seed.tech.tch17 / 100;
			y = (z * y) / (1 - z);
			var min = Math.min(y, 1);
			min = Math.round(min * 10000) / 100;
			return min;
		}
	
		if(t.viewstats == null)
			t.viewstats = new CPopup ('pbviewthronestats', 0, 0, 900, 800, true);
		t.viewstats.centerMe (mainPop.getMainDiv());
		//Grundwerte
		var e = [
			uW.g_js_strings.throneRoom.common,
			uW.g_js_strings.throneRoom.uncommon,
			uW.g_js_strings.throneRoom.rare,
			uW.g_js_strings.throneRoom.epic,
			uW.g_js_strings.throneRoom.wondrous,
		];
		var z = [{
			id: 0,
			name: uW.g_js_strings.throneRoom.buff_none,
		}, uW.ksoItems["20001"], uW.ksoItems["20002"], uW.ksoItems["20003"], uW.ksoItems["20004"]];
		var n = [{
			id: 0,
			name: uW.g_js_strings.throneRoom.buff_none,
		}, uW.ksoItems["20001"], uW.ksoItems["20002"], uW.ksoItems["20005"], uW.ksoItems["20006"], uW.ksoItems["20019"], uW.ksoItems["20022"]];

		var m= '';
		m += '<TABLE class=pdxTab>';
		m += "<tr>";
		m += '<td colspan=3><b style="color:maroon;">'+culang.viewThroneStatsAdd+'</b></td>';
		m += "</tr>";
		m += "<tr>";
		m += '<td>'+uW.techcost.tch17[0]+':&nbsp;&nbsp;</td>';
		m += '<td>'+Seed.tech.tch17 / 100+'%</td>';		
		m += '<td>(max 0.12%)</td>';	
		m += "</tr>";
		m += "<tr>";
		m += '<td>'+uW.g_js_strings.throneRoom.activity_bonus+':&nbsp;&nbsp;</td>';
		m += '<td>'+(Math.round(uW.cm.HeatUpModel.getModifierPercentage() * 100) / 100)+'%</td>';
		m += '<td>(max 0.15%)</td>';	
		m += "</tr>";
		m += '</table>';
		m += '<br><br>';
		m += '<TABLE width="100%" class=pdxTab>';
		m += "<tr>";
		m += '<td colspan=13><b style="color:maroon;">'+culang.viewThroneStatsUpgrade+'</b></td>';
		m += "</tr>";
		m += "<tr>";
		m += '<td>&nbsp;</td>';
		for (var i = 1; i<15; i++) m+= '<td style="text-align:center;"><b>+'+i+'</b></td>';
		for (var buff = 0; buff < n.length; buff++) {
			m += "<tr>";
			m += '<td>'+n[buff].name+'</td>';	
			for (var i = 1; i<15; i++) {
				m+= '<td style="text-align:center;">'+calc("upgrade",buff, i, n[buff].id)+'%</td>';
			}
			m += "</tr>";		
		}
		m +='</table>';
		m +='<br><br>';
		m += '<TABLE width="100%" class=pdxTab>';
		m += "<tr>";
		m += '<td colspan=13><b style="color:maroon;">'+culang.viewThroneStatsEnhance+'</b></td>';
		m += "</tr>";
		m += "<tr>";
		m += '<td>&nbsp;</td>';
		for (var i = 0; i<5; i++) m+= '<td style="text-align:center;"><b>'+e[i]+'</b></td>';
		for (var buff = 0; buff < z.length; buff++) {
			m += "<tr>";
			m += '<td>'+z[buff].name+'</td>';	
			for (var i = 0; i<5; i++) {
				m+= '<td style="text-align:center;">'+calc("enhance",buff, i+1, z[buff].id)+'%</td>';
			}
			m += "</tr>";		
		}
		m +='</table>';
		m +='<br><br>';
		m +='<div style="text-align:center;"><input type="submit" value="'+culang.viewThroneStatsCalc+'" id="pbThroneStatsCalc"></div>';
		m +='<br><br>';
		m +='<div>'+culang.viewThroneStatsHint+'</div>';
		t.viewstats.getMainDiv().innerHTML = m;
		t.viewstats.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.viewThroneStats+'</div>';
		t.viewstats.show(true);
		ById("pbThroneStatsCalc").addEventListener ('click', function (){
			t.throneChance();
		}, false);			
		
	},

	Salvage : function (){
		var t = Tabs.ThroneStuff;
		try {
			var effects = uW.cm.thronestats.effects;
			m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffSalvageHead+'</div><TABLE width=100%><TR>';

			m+='<TD>';
			m+='<div style="margin-top: 0px;"><INPUT type=submit id=pbsalvage_run value="'+culang.throneStuffAutoSalvage+' = '+(Options.ThroneDeleteItems?''+culang.buttonON+'':''+culang.buttonOFF+'')+'" /></div>';
			m+='<div style="margin-top: 2px; padding-left: 11px;">'+culang.mainIntervall+': <input type=text size=3 id=KsThroneInterval value="'+ThroneOptions.IntervalMin+'" > '+culang.mainMinutes+"</div>";
			m+='<div style="margin-top: 4px;"><INPUT type=submit id=pbsalvage_preview value="'+culang.mainShow+'" /></div>'
			m+='</td>';

			m+='<TD>';
			m+='<div style="margin-top: 2px;">'+culang.throneStuffSalvageKeepFirst+' <INPUT type=text id=SaveXitems size=2 maxlength=3 value='+ ThroneOptions.SalvageV2.SaveXitems +'> '+culang.throneStuffSalvageKeepFirst2+"</div>";
			m+='<div style="margin-top: 2px;">'+culang.throneStuffSalvageKeepSel+' ' + htmlSelector({0:culang.mainNone, 1:uW.g_js_strings.throneRoom.common, 2:uW.g_js_strings.throneRoom.uncommon, 3:uW.g_js_strings.throneRoom.rare, 4:uW.g_js_strings.throneRoom.epic, 5:uW.g_js_strings.throneRoom.wondrous},ThroneOptions.SalvageV2.QualityFilter,'id=Quality')+' '+culang.throneStuffSalvageKeepSel2+'</div>';
			m+='<div style="margin-top: 2px;">'+culang.throneStuffSalvageKeepFam
				+' <input type=checkbox id=KsSType_advisor '+ (ThroneOptions.SalvageV2.TypeFilter.Advisor?'CHECKED ':'') +'>advisor '
				+'<input type=checkbox id=KsSType_banner '+ (ThroneOptions.SalvageV2.TypeFilter.Banner?'CHECKED ':'') +'> banner '
				+'<input type=checkbox id=KsSType_chair '+ (ThroneOptions.SalvageV2.TypeFilter.Chair?'CHECKED ':'') +'> chair '
				+'<input type=checkbox id=KsSType_table '+ (ThroneOptions.SalvageV2.TypeFilter.Table?'CHECKED ':'') +'> table'
				+'<input type=checkbox id=KsSType_window '+ (ThroneOptions.SalvageV2.TypeFilter.Window?'CHECKED ':'') +'> window '
				+'<input type=checkbox id=KsSType_trophy '+ (ThroneOptions.SalvageV2.TypeFilter.Trophy?'CHECKED ':'') +'> trophy '
				+'<input type=checkbox id=KsSType_candelabrum '+ (ThroneOptions.SalvageV2.TypeFilter.Candelabrum?'CHECKED ':'') +'> candelabrum '
				+'<input type=checkbox id=KsSType_hero '+ (ThroneOptions.SalvageV2.TypeFilter.Hero?'CHECKED ':'') +'> hero '
				+culang.throneStuffSalvageKeepFam2+'</div>';
			m+='<div style="margin-top: 2px;">'+'<input type=checkbox id=DeleteXitemsEnabled '+ (ThroneOptions.SalvageV2.DeleteXitems.IsEnabled?'CHECKED ':'') +'/>'+' '+culang.throneStuffSalvageLastXItems+''+' <INPUT type=text id=DeleteXitems size=2 maxlength=2 value='+ ThroneOptions.SalvageV2.DeleteXitems.Value +'> '+''+culang.throneStuffSalvageLastXItems2+''+' '+''+culang.throneStuffSalvageLastXItemsNote+''+"</div>";
			m+='<div style="margin-top: 2px;">'+'<input type=checkbox id=DeleteP1Enabled '+ (ThroneOptions.SalvageV2.LevelP1?'CHECKED ':'') +'/>'+' '+culang.throneStuffSalvageP1+"</div>";
			m+='<div style="margin-top: 2px;">'+'<input type=checkbox id=DeleteCityMin '+ (ThroneOptions.SalvageV2.CityMin?'CHECKED ':'') +'/>'+' '+culang.throneStuffSalvageCM+"</div>";
			m+='</td>';

			m+='<TD>';
			m+='<INPUT id=ShowSalvageHistory type=submit value="'+culang.throneStuffSalvageHistory+'"></td></tr><tr><td colspan=3><sup><span class=boldRed>'+culang.mainImportant+'</span>:</sup> <span class="helpText">'+culang.throneStuffSalvageKeepNote+'</span></table>'
			m+='<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffSalvageKeep+'</div>';
			m+='</td>';
			
			m+='<div style="margin-top: 2px;margin-left: 16px;"> A: '+ htmlSelector({100:"---", 0:culang.throneStuffSalvageKeepEffects1, 2:culang.throneStuffSalvageKeepEffects2, 4:culang.throneStuffSalvageKeepEffects3, 7:culang.throneStuffSalvageKeepEffects4, 8:culang.throneStuffSalvageKeepEffects5},ThroneOptions.SalvageV2.EffectMode,'id=SalvageEffectMode1')+
			'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; % Filter:'+'</div>';
			m+='<div style="margin-top: 2px;margin-left: 16px;"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B: '+ htmlSelector({100:"---", 0:culang.throneStuffSalvageKeepEffects1, 2:culang.throneStuffSalvageKeepEffects2, 4:culang.throneStuffSalvageKeepEffects3, 7:culang.throneStuffSalvageKeepEffects4, 8:culang.throneStuffSalvageKeepEffects5},ThroneOptions.SalvageV2.EffectMode2,'id=SalvageEffectMode2')+'</div>';
			m+='<div style="margin-top: 2px;margin-left: 16px;"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;C: '+ htmlSelector({100:"---", 0:culang.throneStuffSalvageKeepEffects1, 2:culang.throneStuffSalvageKeepEffects2, 4:culang.throneStuffSalvageKeepEffects3, 7:culang.throneStuffSalvageKeepEffects4, 8:culang.throneStuffSalvageKeepEffects5},ThroneOptions.SalvageV2.EffectMode3,'id=SalvageEffectMode3')+'</div>';

			m+='<TABLE width=80% class="pdxTab"><tr style="background-Color:#aaa;text-align:left">';
			m+='<td>&nbsp;</td>';
			m+='<td><b> [A] &nbsp; [B] &nbsp; [C] &nbsp; '+culang.buttonSave+'</b></td>';
			m+='<td>&nbsp;</td>';
			m+='<td><b>'+''+culang.shortMin+' %'+'</b></td>';
			m+='<td>advisor banner chair table window trophy c.brum hero(%)</td>';
			m+='<td><b>'+culang.throneFamily+'</b></td>';
			m+='</tr>';

			for (iEffektId in effects){
				if (typeof(effects[iEffektId]) == "undefined") continue;
				if (typeof(effects[iEffektId][1]) == "undefined") continue;
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId]) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId]={IsEnabled:false,Percent:'',PercentAdvisor:'',PercentBanner :'',PercentChair  :'',PercentTable  :'',PercentWindow :'',PercentTrophy :'',PercentCandelabrum :'',};
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentAdvisor) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentAdvisor='';
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentBanner ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentBanner ='';
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentChair  ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentChair  ='';
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTable  ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTable  ='';
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentWindow ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentWindow ='';
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTrophy ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTrophy ='';				
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentCandelabrum ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentCandelabrum ='';	
				if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentHero ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentHero ='';			
				m+='<tr>';
				m+='<td >&nbsp;</td>';
				m+='<td>'+
					'<INPUT class='+iEffektId+' id="KsS1_'+iEffektId+'" type=checkbox ' + (ThroneOptions.SalvageV2.EffectFilter[iEffektId].IsEnabled ?'CHECKED ':'') +'/> &nbsp;'+
					'<INPUT class='+iEffektId+' id="KsS2_'+iEffektId+'" type=checkbox ' + (ThroneOptions.SalvageV2.EffectFilter[iEffektId].IsEnabled2?'CHECKED ':'') +'/> &nbsp;'+
					'<INPUT class='+iEffektId+' id="KsS3_'+iEffektId+'" type=checkbox ' + (ThroneOptions.SalvageV2.EffectFilter[iEffektId].IsEnabled3?'CHECKED ':'') +'/> &nbsp;'+
					effects[iEffektId][1]+'</td>';
				m+='<td>&nbsp;</td>';
				m+='<td>'+'<INPUT class='+iEffektId+' id="KsSP_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].Percent+'" style="width: 40px;"/>%'+'</td>';
				m+='<td>';
				// % for advisor banner chair table window trophy candelabrum
				m+='<INPUT class='+iEffektId+' id="KsSPAd_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentAdvisor+'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPBa_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentBanner +'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPCh_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentChair  +'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPTa_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTable  +'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPWi_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentWindow +'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPTr_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTrophy +'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPCa_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentCandelabrum +'" style="width: 32px;"/>';
				m+='<INPUT class='+iEffektId+' id="KsSPHe_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentHero +'" style="width: 32px;"/>';
				
				m+='</td>';
				//family
				m+='<td>'+effects[iEffektId]["2"] +'</td>';
				m+='</tr>';
			}

			m+='</table>';
			
			//m+='<pre>'+inspect(effects,4)+'</pre>';
			t.Overv.innerHTML = m;
			
			if (parseIntNan(ById("KsThroneInterval").value)<3) ById("KsThroneInterval").value=3;
			ById("KsThroneInterval").addEventListener('change', function(e){
				if (parseIntNan(ById("KsThroneInterval").value)<3) ById("KsThroneInterval").value=3;
				ThroneOptions.IntervalMin=ById("KsThroneInterval").value;
				saveThroneOptions();
			},false);

			ById("KsSType_advisor").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Advisor=ById("KsSType_advisor").checked;saveThroneOptions();
			},false);
			ById("KsSType_banner").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Banner=ById("KsSType_banner").checked;saveThroneOptions();
			},false);
			ById("KsSType_chair").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Chair=ById("KsSType_chair").checked;saveThroneOptions();
			},false);
			ById("KsSType_table").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Table=ById("KsSType_table").checked;saveThroneOptions();
			},false);
			ById("KsSType_window").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Window=ById("KsSType_window").checked;saveThroneOptions();
			},false);
			ById("KsSType_trophy").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Trophy=ById("KsSType_trophy").checked;saveThroneOptions();
			},false);
			ById("KsSType_candelabrum").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Candelabrum=ById("KsSType_candelabrum").checked;saveThroneOptions();
			},false);
			ById("KsSType_hero").addEventListener('click', function(e){
				ThroneOptions.SalvageV2.TypeFilter.Hero=ById("KsSType_hero").checked;saveThroneOptions();
			},false);
			
			ById("pbsalvage_run").addEventListener('click', function(e){t.toggleSalvage();},false);
			ById("pbsalvage_preview").addEventListener('click', function(e){t.previewSalvage();},false);
			ById('SalvageEffectMode1').addEventListener ('change', function(){
				ThroneOptions.SalvageV2.EffectMode = document.getElementById('SalvageEffectMode1').value;
				saveThroneOptions();
			},false);
			ById('SalvageEffectMode2').addEventListener ('change', function(){
				ThroneOptions.SalvageV2.EffectMode2 = document.getElementById('SalvageEffectMode2').value;
				saveThroneOptions();
			},false);
			ById('SalvageEffectMode3').addEventListener ('change', function(){
				ThroneOptions.SalvageV2.EffectMode3 = document.getElementById('SalvageEffectMode3').value;
				saveThroneOptions();
			},false);

			for (iEffektId in effects){
				if (typeof(effects[iEffektId]) == "undefined") continue;
				ById('KsSP_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].Percent = ById('KsSP_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPAd_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentAdvisor = ById('KsSPAd_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPBa_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentBanner = ById('KsSPBa_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPCh_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentChair = ById('KsSPCh_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPTa_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentTable = ById('KsSPTa_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPWi_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentWindow = ById('KsSPWi_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPTr_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentTrophy = ById('KsSPTr_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPCa_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentCandelabrum = ById('KsSPCa_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				ById('KsSPHe_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentHero = ById('KsSPHe_'+e.target['className']).value;
					saveThroneOptions();
				},false);
				
				ById('KsS1_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].IsEnabled = ById('KsS1_'+e.target['className']).checked;
					saveThroneOptions();
				},false);
				ById('KsS2_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].IsEnabled2 = ById('KsS2_'+e.target['className']).checked;
					saveThroneOptions();
				},false);
				ById('KsS3_'+iEffektId).addEventListener ('change', function(e){
					ThroneOptions.SalvageV2.EffectFilter[e.target['className']].IsEnabled3 = ById('KsS3_'+e.target['className']).checked;
					saveThroneOptions();
				},false);
			}
			
			document.getElementById('Quality').addEventListener  ('change', function(){ThroneOptions.SalvageV2.QualityFilter = this.value;saveThroneOptions();},false);
			document.getElementById('ShowSalvageHistory').addEventListener('click', function(){t.PaintSalvageHistory()} , false);
			document.getElementById('SaveXitems').addEventListener('change', function(){ThroneOptions.SalvageV2.SaveXitems = document.getElementById('SaveXitems').value;saveThroneOptions();} , false);
			document.getElementById('DeleteXitemsEnabled').addEventListener('change', function(){ThroneOptions.SalvageV2.DeleteXitems.IsEnabled = document.getElementById('DeleteXitemsEnabled').checked;saveThroneOptions();} , false);
			document.getElementById('DeleteP1Enabled').addEventListener('change', function(){
				ThroneOptions.SalvageV2.LevelP1 = document.getElementById('DeleteP1Enabled').checked;
				saveThroneOptions();
			} , false);
			document.getElementById('DeleteCityMin').addEventListener('change', function(){
				ThroneOptions.SalvageV2.CityMin = document.getElementById('DeleteCityMin').checked;
				saveThroneOptions();
			} , false);
			document.getElementById('DeleteXitems').addEventListener('change', function(){
				if(parseIntNan(document.getElementById('DeleteXitems').value)<2)document.getElementById('DeleteXitems').value=2;
				ThroneOptions.SalvageV2.DeleteXitems.Value = document.getElementById('DeleteXitems').value;saveThroneOptions();
			}, false);

		} catch (ex) {
			t.Overv.innerHTML = '<PRE>'+ ex.name + ': ' + ex.message + " @" + ex.lineNumber +'</pre>';
		}
	},
	toggleSalvage:function() {
		var t = Tabs.ThroneStuff;
		if(Options.ThroneDeleteItems){
			if(ById("pbsalvage_run")) ById("pbsalvage_run").value = culang.throneStuffAutoSalvage+" = "+culang.buttonOFF;
			Options.ThroneDeleteItems = false;
			saveOptions();saveThroneOptions();
			clearTimeout(t.timersalvage);
		} else {
			if (ById("pbsalvage_run")) ById("pbsalvage_run").value = culang.throneStuffAutoSalvage+" = "+culang.buttonON;
			Options.ThroneDeleteItems = true;
			t.SalvageRunning=false;
			t.SalvageArray=[];
			t.SalvageArrayP1=[];
			t.LastDeleted=0;
			t.salvageCheck();
			saveOptions();saveThroneOptions();
		}
	},

	previewSalvage:function() {
		// <summary> Handler of Salvage Preview Button </summary>
		var t = Tabs.ThroneStuff;
		if(Options.ThroneDeleteItems) {
			clearTimeout(t.timersalvage);
			t.toggleSalvage();
		}
		t.SalvagePreviewMode=true;
		t.salvageCheck();
		t.SalvagePreviewMode=false;
	},
	Upgrade_Enhance :function (){
		var t = Tabs.ThroneStuff;
		//try {
		var m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffEUHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center">';
		if (ThroneOptions.Active == false) {
			m += '<TD><INPUT id=Enable type=submit value="'+culang.throneStuffEUQueueEnable+' = '+culang.buttonOFF+'"></td>';
		} else {
			m += '<TD><INPUT id=Enable type=submit value="'+culang.throneStuffEUQueueEnable+' = '+culang.buttonON+'"></td>';
		}
		m += '<TD><INPUT id=ShowHistory type=submit value="'+culang.throneStuffEUQueueHistory+'"></td>';
		m += '<td style="text-align:left;"><input type=checkbox id=CitySelMax '+ (ThroneOptions.CityMax?'CHECKED ':'') +'/>'+' '+culang.throneStuffCityMax+"</td></tr>";
		//m += '<tr><td></td><td></td><td style="text-align:left;">';
		//m += '<input type=checkbox id=ThroneRepairAll '+ (ThroneOptions.RepairAll?'CHECKED ':'') +'/>'+' '+culang.throneStuffRepairAll;
		//m += '</td></tr>';
		m += '<tr><td></td><td></td><td style="text-align:left;">';
		m += '<input type=checkbox id=Throne20001 '+ (ThroneOptions.i20001?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20001.jpg" width=30 title="'+uW.itemlist.i20001.name+' - '+uW.itemlist.i20001.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20002 '+ (ThroneOptions.i20002?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20002.jpg" width=30 title="'+uW.itemlist.i20002.name+' - '+uW.itemlist.i20002.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20005 '+ (ThroneOptions.i20005?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20005.jpg" width=30 title="'+uW.itemlist.i20005.name+' - '+uW.itemlist.i20005.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20006 '+ (ThroneOptions.i20006?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20006.jpg" width=30 title="'+uW.itemlist.i20006.name+' - '+uW.itemlist.i20006.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20003 '+ (ThroneOptions.i20003?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20003.jpg" width=30 title="'+uW.itemlist.i20003.name+' - '+uW.itemlist.i20003.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20004 '+ (ThroneOptions.i20004?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20004.jpg" width=30 title="'+uW.itemlist.i20004.name+' - '+uW.itemlist.i20004.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20019 '+ (ThroneOptions.i20019?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20019.jpg" width=30 title="'+uW.itemlist.i20019.name+' - '+uW.itemlist.i20019.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20022 '+ (ThroneOptions.i20022?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20022.jpg" width=30 title="'+uW.itemlist.i20022.name+' - '+uW.itemlist.i20022.description+'">&nbsp;&nbsp;';
		m += '<br>';
		m += '<input type=checkbox id=Throne20012 '+ (ThroneOptions.i20012?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20012.jpg" width=30 title="'+uW.itemlist.i20012.name+' - '+uW.itemlist.i20012.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20013 '+ (ThroneOptions.i20013?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20013.jpg" width=30 title="'+uW.itemlist.i20013.name+' - '+uW.itemlist.i20013.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20014 '+ (ThroneOptions.i20014?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20014.jpg" width=30 title="'+uW.itemlist.i20014.name+' - '+uW.itemlist.i20014.description+'">&nbsp;&nbsp;';
		
		m += '<input type=checkbox id=Throne20015 '+ (ThroneOptions.i20015?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20015.jpg" width=30 title="'+uW.itemlist.i20015.name+' - '+uW.itemlist.i20015.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20016 '+ (ThroneOptions.i20016?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20016.jpg" width=30 title="'+uW.itemlist.i20016.name+' - '+uW.itemlist.i20016.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20017 '+ (ThroneOptions.i20017?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20017.jpg" width=30 title="'+uW.itemlist.i20017.name+' - '+uW.itemlist.i20017.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20018 '+ (ThroneOptions.i20018?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20018.jpg" width=30 title="'+uW.itemlist.i20018.name+' - '+uW.itemlist.i20018.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20020 '+ (ThroneOptions.i20020?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20020.jpg" width=30 title="'+uW.itemlist.i20020.name+' - '+uW.itemlist.i20020.description+'">&nbsp;&nbsp;';
		m += '<input type=checkbox id=Throne20021 '+ (ThroneOptions.i20021?'CHECKED ':'') +'> ';
		m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20021.jpg" width=30 title="'+uW.itemlist.i20021.name+' - '+uW.itemlist.i20021.description+'">';
		m += '</td></tr>';
		m += '<tr><td></td><td style="text-align:left;">';
		m += '<td><input id=pbThroneStuffSpeed type=checkbox>&nbsp;'+culang.throneStuffUseSpeedups+'</td>';		
		m += '</tr>';
		m+= '</tr></table>';
		
		m+= '<DIV class=pdxStat>'+culang.throneStuffItemStats+'</div>';
		m+= '<div id="ThroneItemsStats"></div>';
		
		m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffEUQueueAdd+'</div><TABLE class=pdxTab><br/>';
		m+='<TR><TD>'+culang.throneStuffEUQueueThroneItems+'<br><br><SELECT id=ThroneItems type=list>';
		
		var nb=0,couleur=0;
		for (i in uW.kocThroneItems){
			nb++
			var styleee="background-color:#FFF";
			if (uW.kocThroneItems[i].isEquipped) {
				styleee="background-color:#99DC99";
				if (nb==1) couleur=1;
			}else if (uW.kocThroneItems[i].isBroken) {
				styleee="background-color:#DC9999";
			}

			if (nb>(parseInt(Seed.throne.rowNum)*5)) break;
			var faction=uW.kocThroneItems[i].faction;
			var type=uW.kocThroneItems[i].type;
			if(faction=="briton")faction="britton";//Kabam bug workaround
			var imagesrc='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/'+faction+'/'+faction+'_'+type+'_normal_1.png'; 
			m+="<option style='"+styleee+"' value="+uW.kocThroneItems[i]["id"]+"> "+(nb<10?"&nbsp;&nbsp;":"")+nb+". "+getThroneItemName(i)+"</option>";
		}

		m+='</select>'
		m+='<br><br>'
		m+='<INPUT id=addEnhance type=submit value="'+culang.throneStuffEnhance+'">';
		m+='<INPUT id=addUpgrade type=submit value="'+culang.throneStuffUpgrade+'">';
		m+='</td>';
		m+='<TD><DIV id=ShowHoover></div></td>';
		m+='</tr></table><br/>';
		m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffHeadStats+'</div>';
		m+= '<br/><DIV id=ShowStatus></div></p>';
		m+= '<DIV id=ShowTries></div><br/>';
		m+= '<DIV id=ShowStones></div><br/>';
		m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffHeadUpgradeInfo+'</div>';
		m+= '<br/><DIV id=ShowInfo></div><br/>';
		m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffHeadQueue+'</div>';
		m+= '<br/><DIV id=ShowQueueDiv></div>';
		t.Overv.innerHTML = m;
		if (couleur==1) ById("ThroneItems").style.backgroundColor="#99DC99"
		document.getElementById('CitySelMax').addEventListener('change', function(){
			ThroneOptions.CityMax = document.getElementById('CitySelMax').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20001').addEventListener('change', function(){
			ThroneOptions.i20001 = document.getElementById('Throne20001').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20002').addEventListener('change', function(){
			ThroneOptions.i20002 = document.getElementById('Throne20002').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20003').addEventListener('change', function(){
			ThroneOptions.i20003 = document.getElementById('Throne20003').checked;
			saveThroneOptions();
		} , false);	
		document.getElementById('Throne20004').addEventListener('change', function(){
			ThroneOptions.i20004 = document.getElementById('Throne20004').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20005').addEventListener('change', function(){
			ThroneOptions.i20005 = document.getElementById('Throne20005').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20006').addEventListener('change', function(){
			ThroneOptions.i20006 = document.getElementById('Throne20006').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20019').addEventListener('change', function(){
			ThroneOptions.i20005 = document.getElementById('Throne20019').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20022').addEventListener('change', function(){
			ThroneOptions.i20006 = document.getElementById('Throne20022').checked;
			saveThroneOptions();
		} , false);	
		document.getElementById('Throne20012').addEventListener('change', function(){
			ThroneOptions.i20012 = document.getElementById('Throne20012').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20013').addEventListener('change', function(){
			ThroneOptions.i20013 = document.getElementById('Throne20013').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20014').addEventListener('change', function(){
			ThroneOptions.i20014 = document.getElementById('Throne20014').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20015').addEventListener('change', function(){
			ThroneOptions.i20012 = document.getElementById('Throne20015').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20016').addEventListener('change', function(){
			ThroneOptions.i20013 = document.getElementById('Throne20016').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20017').addEventListener('change', function(){
			ThroneOptions.i20014 = document.getElementById('Throne20017').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20018').addEventListener('change', function(){
			ThroneOptions.i20012 = document.getElementById('Throne20018').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20020').addEventListener('change', function(){
			ThroneOptions.i20013 = document.getElementById('Throne20020').checked;
			saveThroneOptions();
		} , false);
		document.getElementById('Throne20021').addEventListener('change', function(){
			ThroneOptions.i20014 = document.getElementById('Throne20021').checked;
			saveThroneOptions();
		} , false);

		document.getElementById('addEnhance').addEventListener ('click', function (){t.addToQueue(document.getElementById('ThroneItems').value,""+culang.throneStuffEnhance+"");},false);
		document.getElementById('addUpgrade').addEventListener ('click', function (){t.addToQueue(document.getElementById('ThroneItems').value,""+culang.throneStuffUpgrade+"");},false);
		document.getElementById('ThroneItems').addEventListener ('change', function (){t.paintHoover();},false);
		document.getElementById('Enable').addEventListener('click', function(){t.toggleThroneState()} , false);
		document.getElementById('ShowHistory').addEventListener('click', function(){t.PaintHistory()} , false);
		t.togOpt("pbThroneStuffSpeed","throneUseSpeedups");
		if (ThroneOptions.Items.length ==0 && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoItems+"</i>";
		else {
			if (ThroneOptions.Active && Seed.queue_throne.end == undefined && ById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueWaiting+"</i>";
			if (ThroneOptions.Active && Seed.queue_throne.end != undefined && ById('ShowStatus')) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
			if (!ThroneOptions.Active && Seed.queue_throne.end != undefined && ById('ShowStatus')) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
			if (!ThroneOptions.Active && Seed.queue_throne.end == undefined && ById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
		}
		if (ThroneOptions.Tries > 0) document.getElementById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTries+" " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
		else document.getElementById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTriesNone+"";
		if (ThroneOptions.Items.length>0) { // && ThroneOptions.Tries > 0) {
			t.PaintQueue();
			t.paintInfo();
		}
		t.paintStones();
		t.paintHoover();
		setInterval(t.paintStones,2000);
		setInterval(t.paintThroneItemStats,2000);
		clearTimeout(t.timer);
		t.timer = setTimeout(t.UseSpeedup, 9000);
	},
	togOpt : function (checkboxId, optionName, callOnChange){
		var t = Tabs.Options;
		var checkbox = ById(checkboxId);
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (callOnChange)
				callOnChange (this.checked);
		}
	},
	paintThroneItemStats: function() {
		var t = Tabs.ThroneStuff;
		try {
		var out = ById("ThroneItemsStats");
		if (out) {
			out.style.border = "1px solid silver";
			out.style.margin = "5px 0";
			var item = [20001, 20002, 20005, 20006, 20003, 20004, 20019, 20022, 20012, 20013, 20014, 20015, 20016, 20017, 20018, 20020, 20021];
			m = '<table width=100%><tr>';
			for (var i = 0; i< item.length; i++) {
				var ii = item[i];
				m += '<td style="text-align:center; width:5.8%;"><img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/'+ii+'.jpg" width=40 title="'+uW.itemlist['i'+ii].name+' - '+uW.itemlist['i'+ii].description+'"><br>'+addCommas(parseIntNan(Seed.items['i'+ii]))+'</td>';
			}
			m += '</tr></table>';
			out.innerHTML = m;
		}
		} catch (ex) {
			t.Overv.innerHTML = '<PRE>'+ ex.name + ': ' + ex.message + " @" + ex.lineNumber +'</pre>';
		}
	},
	Equip :function (){
		var t = Tabs.ThroneStuff;
		try {
			var m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffEquipHead+'</div><br>';
			m+='<DIV align=center>'+culang.throneStuffEquipPreset+' <SELECT id=preset type=list></select></div><br><TABLE width=100% height=0% class=pdxTab>';
			for (k in t.EquipType){
				var y = t.EquipType[k];
				if (typeof(y) == "string") {
					what = y.toLowerCase();
					if (y == "Windows") y = "Window";
					m+='<TR><TD>'+ y +':</td><TD></td><TD><SELECT id='+ what +' type=list></select></td><TD><INPUT id="Equip'+ what +'" type=submit value="'+culang.throneStuffEquip+'"></td><TD><INPUT id="Unequip'+ what +'" type=submit value="'+culang.throneUnequipItem+'"></td><TD><div id="info'+ what +'"</td></tr><TR><TD>&nbsp;</td></tr><TR><TD>&nbsp;</td></tr>';
				}
			}
			m+="</table>"
			t.Overv.innerHTML = m;
			document.getElementById("preset").options.length=0;
			for (i=1;i<=Seed.throne.slotNum;i++){
				var o = document.createElement("option");
				o.text = i;
				o.value = i;
				document.getElementById("preset").options.add(o);
			}
			document.getElementById("advisor").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("advisor").value,"advisor")},false);
			document.getElementById("banner").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("banner").value,"banner")},false);
			document.getElementById("chair").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("chair").value,"chair")},false);
			document.getElementById("table").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("table").value,"table")},false);
			document.getElementById("windows").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("windows").value,"windows")},false);
			document.getElementById("trophy").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("trophy").value,"trophy")},false);
			document.getElementById("candelabrum").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("candelabrum").value,"candelabrum")},false);
			document.getElementById("hero").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("hero").value,"hero")},false);

			document.getElementById("Equipadvisor").addEventListener ('click', function (){t.doEquip(document.getElementById("advisor").value)},false);
			document.getElementById("Equipbanner").addEventListener ('click', function (){t.doEquip(document.getElementById("banner").value)},false);
			document.getElementById("Equipchair").addEventListener ('click', function (){t.doEquip(document.getElementById("chair").value)},false);
			document.getElementById("Equiptable").addEventListener ('click', function (){t.doEquip(document.getElementById("table").value)},false);
			document.getElementById("Equipwindows").addEventListener ('click', function (){t.doEquip(document.getElementById("windows").value)},false);
			document.getElementById("Equiptrophy").addEventListener ('click', function (){t.doEquip(document.getElementById("trophy").value)},false);
			document.getElementById("Equipcandelabrum").addEventListener ('click', function (){t.doEquip(document.getElementById("candelabrum").value)},false);
			document.getElementById("Equiphero").addEventListener ('click', function (){t.doEquip(document.getElementById("hero").value)},false);
			
			document.getElementById("Unequipadvisor").addEventListener ('click', function (){t.doUnequip(document.getElementById("advisor").value)},false);
			document.getElementById("Unequipbanner").addEventListener ('click', function (){t.doUnequip(document.getElementById("banner").value)},false);
			document.getElementById("Unequipchair").addEventListener ('click', function (){t.doUnequip(document.getElementById("chair").value)},false);
			document.getElementById("Unequiptable").addEventListener ('click', function (){t.doUnequip(document.getElementById("table").value)},false);
			document.getElementById("Unequipwindows").addEventListener ('click', function (){t.doUnequip(document.getElementById("windows").value)},false);
			document.getElementById("Unequiptrophy").addEventListener ('click', function (){t.doUnequip(document.getElementById("trophy").value)},false);
			document.getElementById("Unequipcandelabrum").addEventListener ('click', function (){t.doUnequip(document.getElementById("candelabrum").value)},false);
			document.getElementById("Unequiphero").addEventListener ('click', function (){t.doUnequip(document.getElementById("hero").value)},false);
			
			document.getElementById("preset").addEventListener ('change', function (){t.doPreset(document.getElementById("preset").value)},false);
			document.getElementById("preset").value = Seed.throne.activeSlot;
			t.FillEquipCheckboxes();
		} catch (ex) {
			t.Overv.innerHTML = '<PRE>'+ ex.name + ': ' + ex.message + " @" + ex.lineNumber +'</pre>';
		}
	},

	FillEquipCheckboxes: function(){
		var t = Tabs.ThroneStuff;
		for (k in t.EquipType) {
			var y = t.EquipType[k];
			var itemEquiped = 0;
			var count = 0;
			if (typeof(y) == "string") {
				what = y.toLowerCase();
				document.getElementById(what).options.length=0;
				for (l in uW.kocThroneItems) {
					effects = uW.kocThroneItems[l];
					check = what;
					if (check == "windows") check = "window";
					count++;
					if (count<=(parseInt(Seed.throne.rowNum)*5)){
						if (effects.type == check && effects.isBroken==false) {
							var o = document.createElement("option");
							o.text = getThroneItemName(l);
							o.value = l;
							document.getElementById(what).options.add(o);
							if (effects.isEquipped) itemEquiped = l;
						}
					}

				}
				if (document.getElementById(what).options.length == 0){
					var o = document.createElement("option");
					o.text = ""+culang.throneStuffEquipNoItemsAvailable+" " + check + " "+culang.throneStuffEquipNoItemsAvailable2+"";
					o.value = 1;
					document.getElementById(what).options.add(o);
					itemEquiped = 1;
				} else if (itemEquiped == 0) {
					var o = document.createElement("option");
					o.text = ""+culang.throneStuffEquipNoItems+" " + check + " "+culang.throneStuffEquipNoItems2+"";
					o.value = 2;
					document.getElementById(what).options.add(o);
					document.getElementById('info'+what).innerHTML = "";
					itemEquiped = 2;
				}
				//logit(what + ' / ' + itemEquiped);
				document.getElementById(what).value = itemEquiped;
			}

			switch(itemEquiped){
				case 0:
					break;
				case 1:
					document.getElementById("Equip"+what).disabled = true;
					document.getElementById("Unequip"+what).disabled = true;
					break;
				case 2:
					document.getElementById("Equip"+what).disabled = false;
					document.getElementById("Unequip"+what).disabled = true;
					break;
				default:
					document.getElementById("Equip"+what).disabled = true;
					document.getElementById("Unequip"+what).disabled = false;
					t.paintEquipInfo(ById(what).value,what);
					break;
			}

		}
	},

	doPreset : function (preset){
		var t = Tabs.ThroneStuff;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'setPreset';
		params.presetId = preset;

		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if(rslt.ok){
					button = '<li id="throneInventoryPreset' + preset + '" class="active">'+preset+'</li>';
					uW.cm.ThroneView.clickActivePreset(button);
					t.FillEquipCheckboxes();
				}
			},
			onFailure: function () {
				return;
			},
		});

	},

	paintEquipInfo : function (z,what){
		var t = Tabs.ThroneStuff;
		var m="";
		if (typeof(uW.kocThroneItems[z]) == 'object') {
			var y = uW.kocThroneItems[z];
		} else return;
		var id =0;
		var tier=0;
		var Current=0;
		m="<TABLE width=80% height=0% align='center' class=pdxTab>";
		for (i=1;i<=5;i++) {
			id = y["effects"]["slot"+i]["id"];
			tier = parseInt(y["effects"]["slot"+i]["tier"]);
			level = y["level"];
			p = false;
			while (!p && (tier > -1)) {
				p = uW.cm.thronestats.tiers[id][tier];
				tier--;
			}
   		var base = p.base || 0;
			var growth = p.growth ||0;
			Current = base + ((level * level + level) * growth * 0.5);
			var quality = parseInt(y["quality"]);
			if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			else m+='<TR><TD><FONT color=red>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
		}
		m+="</table>"

		ById('info'+what).innerHTML = m;
	},

	Stats :function (){
		var t = Tabs.ThroneStuff;
		try {
			m= '<DIV class=pdxStat>'+culang.throneStuffHeadStats+'</div><center><table border=0 width=75%><tr><td colspan=3 style="text-align:right"></td></tr>';
			var k=Seed.throne.slotEquip[Seed.throne.activeSlot]; //TODO rename k
			var B=0, w={}, x, C; //TODO rename B, w, x, C
			for (var K in k) { //TODO rename K
				var item = uW.kocThroneItems[k[K]];
				if (item) {
					x=0;

					for (var M in item.effects) {//TODO rename M
						x++;
						if (item.quality >= x) {
							B++;
							I = uW.cm.thronestats.effects[item.effects[M].id];
							var id = item.effects[M].id;
							var tier = item.effects[M].tier;
							p = false;
							while (!p && (tier > -1)) {
								p = uW.cm.thronestats.tiers[id][tier];
								tier--;
							}
							var base = p.base || 0;
							var growth = p.growth ||0;
							C = + base + (item.level * item.level + item.level) * + growth * 0.5;
							// C = Math.ceil(C);
							if (!item.isBroken) {
								if (!w[item.effects[M].id]) {
									w[item.effects[M].id] = {};
									w[item.effects[M].id].nameitem="";
								}
								if (!w[item.effects[M].id].percent) {
									w[item.effects[M].id].percent = C;
								} else {
									w[item.effects[M].id].percent += C;
								}
								w[item.effects[M].id].name = I[1];
								w[item.effects[M].id].nameitem += "(" + getThroneItemName(item.id) + ")<br>";
							}
						}
					}
				}
			}
			B = 0;
			for (var K in w) {
				var Current =  Math.round(w[K].percent*100)/100;
				G="<tr><td align=right><b>"+ Current + " %</b></td><td align=left>" + w[K].name + "</td><td>"+w[K].nameitem+"</td></tr>";
				m+=G;
			}
			t.Overv.innerHTML = m;
		} catch (ex) {
			t.Overv.innerHTML = '<PRE>'+ ex.name + ': ' + ex.message + " @" + ex.lineNumber +'</pre>';
		}
	},

	togOpt : function (checkboxId, optionName, callOnChange){
		var t = Tabs.ThroneStuff;
		var checkbox = ById(checkboxId);
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (callOnChange)
				callOnChange (this.checked);
		}
	},

	changeOpt : function (valueId, optionName, callOnChange){
		var t = Tabs.ThroneStuff;
		var e = ById(valueId);
		e.value = Options[optionName];
		e.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.value;
			saveOptions();
			if (callOnChange)
				callOnChange (this.value);
		}
	},

	toggleThroneState: function(){
		var t = Tabs.ThroneStuff;
		if (Options.salvageconfig.Repairrunning ==true) {
			alert(culang.throneStuffEUNotPossible);
			return;
		}
		if (ThroneOptions.Active == true) {
			ThroneOptions.Active = false;
			if(ById("Enable")) ById('Enable').value = culang.throneStuffEUQueueEnable+' = '+culang.buttonOFF;
			saveThroneOptions();
			clearTimeout(t.setActionTimer);
			if (Seed.queue_throne.end == undefined && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
		} else {
			ThroneOptions.Active = true;
			if(ById("Enable")) ById('Enable').value = culang.throneStuffEUQueueEnable+' = '+culang.buttonON;
			saveThroneOptions();
			t.setActionTimer = setInterval(t.doAction,2000);
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueWaiting+"</i>";
		}
	},

	_addTab: function(id,name,qualityfrom,qualityto,levelfrom,levelto,action,active,cost){
		var t = Tabs.ThroneStuff;
		var a="";
		var b="";
		switch (qualityfrom) {
			case 0:a = uW.g_js_strings.throneRoom.simple;break;
			case 1:a = uW.g_js_strings.throneRoom.common;break;
			case 2:a = uW.g_js_strings.throneRoom.uncommon;break;
			case 3:a = uW.g_js_strings.throneRoom.rare;break;
			case 4:a = uW.g_js_strings.throneRoom.epic;break;
			case 5:a = uW.g_js_strings.throneRoom.wondrous;break;
			case 6:a = uW.g_js_strings.throneRoom.unique;break;
			default:a = uW.g_js_strings.throneRoom.simple;break;
		}
		switch (qualityto) {
			case 0:b = uW.g_js_strings.throneRoom.simple;break;
			case 1:b = uW.g_js_strings.throneRoom.common;break;
			case 2:b = uW.g_js_strings.throneRoom.uncommon;break;
			case 3:b = uW.g_js_strings.throneRoom.rare;break;
			case 4:b = uW.g_js_strings.throneRoom.epic;break;
			case 5:b = uW.g_js_strings.throneRoom.wondrous;break;
			case 6:a = uW.g_js_strings.throneRoom.unique;break;
			default:b = uW.g_js_strings.throneRoom.simple;break;
		}
		if (document.getElementById('ShowQueue')) {
			var row = ById('ShowQueue').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			if (active) row.style.color = "green";
			row.insertCell(0).innerHTML = id+1;
			row.insertCell(1).innerHTML = name;
			if (action == ""+culang.throneStuffEnhance+"") {
				row.insertCell(2).innerHTML = a + " -> " + b;
				row.insertCell(3).innerHTML = levelfrom;
			}
			if (action == ""+culang.throneStuffUpgrade+"") {
				row.insertCell(2).innerHTML = a;
				row.insertCell(3).innerHTML = levelfrom + " -> " + levelto;
			}
			row.insertCell(4).innerHTML = action;
			row.insertCell(5).innerHTML = cost;
			row.insertCell(6).innerHTML = '<a id="queueDelete_' + id + '"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a>';
			ById('queueDelete_' + id).addEventListener('click', function(){
				// if (ThroneOptions.Items[id].active ==true) ThroneOptions.Tries=0;
			if (ThroneOptions.Items.length ==0 && ThroneOptions.Active && ById('ShowStatus')) {
			   document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoItems+"</i>";
			 }
			if (!ThroneOptions.Active && ById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
			ThroneOptions.Items.splice (id,1);
				saveThroneOptions();
				t.checkUpgradeInfo(false);
				t.PaintQueue();
				if (ThroneOptions.Items.length>0) t.paintInfo();
				else ById('ShowInfo').innerHTML = "";
			}, false);

		}
	},

	_addTabHeader: function() {
		var t = Tabs.ThroneStuff;
		if (ById('ShowQueue')) {
			var row = ById('ShowQueue').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			row.insertCell(0).innerHTML = "<b><u>"+culang.throneStuffId+"</u></b>";
			row.insertCell(1).innerHTML = "<b><u>"+culang.mainName+"</u></b>";
			row.insertCell(2).innerHTML = "<b><u>"+culang.throneQuality+"</u></b>";
			row.insertCell(3).innerHTML = "<b><u>"+culang.throneLevel+"</u></b>";
			row.insertCell(4).innerHTML = "<b><u>"+culang.throneAction+"</u></b>";
			row.insertCell(5).innerHTML = "<b><u>"+culang.throneStuffCost+"</u></b>";
			row.insertCell(6).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		}
	},

	PaintHistory : function() {
		var t = Tabs.ThroneStuff;
		var popHistory = null;
		popHistory = new CPopup('pbShowHistory', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=2 cellspacing=2 width=100% class="pbShowBarbs" id="pbBars1">';
		popHistory.getMainDiv().innerHTML = '</table></div>' + m;
		popHistory.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.throneStuffUpgradeEnhanceList+'</div>';
		for (i=0;i<t.log.length;i++){
			var row = ById('pbBars1').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			row.insertCell(0).innerHTML = t.log[i].time;
			row.insertCell(1).innerHTML = t.log[i].name;
			row.insertCell(2).innerHTML = t.log[i].action;
			row.insertCell(3).innerHTML = t.log[i].tries;
			row.insertCell(4).innerHTML = t.log[i].good;
			row.insertCell(5).innerHTML = t.log[i].bad;
		}
		var row = ById('pbBars1').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.insertCell(0).innerHTML = "<b><u>"+culang.mainTime+"</u></b>";
		row.insertCell(1).innerHTML = "<b><u>"+culang.mainName+"</u></b>";
		row.insertCell(2).innerHTML = "<b><u>"+culang.throneAction+"</u></b>";
		row.insertCell(3).innerHTML = "<b><u>"+culang.throneStuffTries+"</u></b>";
		row.insertCell(4).innerHTML = "<b><u>"+culang.throneStuffGoodReq+"</u></b>";
		row.insertCell(5).innerHTML = "<b><u>"+culang.throneStuffBadReq+"</u></b>";
		popHistory.show(true)	;
	},

	PaintSalvageHistory : function() {
		var t = Tabs.ThroneStuff;
		try {
		var popHistory = null;
		popHistory = new CPopup('pbSalvageShowHistory', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=2 cellspacing=2 width=100% class="pbShowBarbs" id="pbBars2">';
		popHistory.getMainDiv().innerHTML = '</table></div>' + m;
		popHistory.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.throneStuffSalvageList+'</div>';
		for (i=0;i<t.SalvageLog.length;i++){
			var row = ById('pbBars2').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			row.insertCell(0).innerHTML = t.SalvageLog[i].time;
			row.insertCell(1).innerHTML = t.SalvageLog[i].stones;
			row.insertCell(2).innerHTML = t.SalvageLog[i].msg;
		}
		var row = ById('pbBars2').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.insertCell(0).innerHTML = "<b><u>"+culang.mainTime+"</u></b>";
		row.insertCell(1).innerHTML = "<img height=18 src='"+IMGastone30+"' title='"+uW.g_js_strings.commonstr.aetherstone+"'>";
		row.insertCell(2).innerHTML = "<b><u>"+culang.throneAction+"</u></b>";
		popHistory.show(true)	;
		} catch(ex) {
			alert('10845/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
	},

	PaintSalvagePreview : function() {
		var t = Tabs.ThroneStuff;
		var popPreview = null;
		popPreview = new CPopup('pbSalvageShowPreview', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto">';
		m+='<div>'+culang.mainShow+': <input type="checkbox" id="SalvagePreviewShowDel" '+(ThroneOptions.SalvageV2.Preview.ShowDel?'checked':'')+' /> '+culang.throneStuffSalvagePreviewDeleteKeep+' <input type="checkbox" id="SalvagePreviewShowKeep" '+(ThroneOptions.SalvageV2.Preview.ShowKeep?'checked':'')+' /> '+culang.throneStuffSalvagePreviewDeleteKeep2+'</div>'
		m+='<div>'+culang.throneStuffSalvagePreviewDeleteKeepNote+'</div>'
		m+='<TABLE align=center cellpadding=2 cellspacing=2 width=100% class="pbShowBarbs" id="pbBars3"></table>';
		m+='</div>';
		popPreview.getMainDiv().innerHTML = m;
		ById("SalvagePreviewShowDel").addEventListener ('change', function(){
			var t = Tabs.ThroneStuff;
			ThroneOptions.SalvageV2.Preview.ShowDel = ById("SalvagePreviewShowDel").checked;
			saveThroneOptions();
			t.PaintSalvagePreview();
		},false);
		ById("SalvagePreviewShowKeep").addEventListener ('change', function(){
			var t = Tabs.ThroneStuff;
			ThroneOptions.SalvageV2.Preview.ShowKeep = ById("SalvagePreviewShowKeep").checked;
			saveThroneOptions();
			t.PaintSalvagePreview();
		},false);

		popPreview.getTopDiv().innerHTML = '<DIV class="popupBanner">'+""+culang.throneStuffSalvagePreviewHead+""+'</div>';
		for (i=t.SalvagePreviewList.length-1;i>=0;i--){
			if(!((ThroneOptions.SalvageV2.Preview.ShowDel && t.SalvagePreviewList[i].del) ||
				(ThroneOptions.SalvageV2.Preview.ShowKeep && !t.SalvagePreviewList[i].del))) continue;
			var row = ById('pbBars3').insertRow(0);
			row.vAlign = 'top';
			row.style.color = "black";
			row.insertCell(0).innerHTML = t.SalvagePreviewList[i].number+(t.SalvagePreviewList[i].del?"":"* ")+(t.SalvagePreviewList[i].isInFreeRow?'':' !'); ;
			row.insertCell(1).innerHTML = "";//t.SalvagePreviewList[i].stones;
			row.insertCell(2).innerHTML = t.SalvagePreviewList[i].msg;
			row.insertCell(3).innerHTML = t.SalvagePreviewList[i].keepReason;
		}
		var row = ById('pbBars3').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.insertCell(0).innerHTML = "#";
		row.insertCell(1).innerHTML = "<img height=18 src='"+IMGastone30+"' title='"+uW.g_js_strings.commonstr.aetherstone+"'>";
		row.insertCell(2).innerHTML = "<b><u>"+culang.throneHeadItemList+"</u></b>";
		row.insertCell(3).innerHTML = "?";
		popPreview.show(true);
	},
	
	addToQueue : function (id,action){
		var t= Tabs.ThroneStuff;
		if (ById('ShowHoover')) ById('ShowHoover').innerHTML = "";
		ThroneOptions.Items.push ({
			id:id,
			action:action,
			name:getThroneItemName(id),
			qualityfrom:0,
			qualityto:0,
			levelfrom:0,
			levelto:0,
			cost:0,
			active:false
		});
		saveThroneOptions();
		t.checkUpgradeInfo(false);

		if (ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNextItem+"</i>"
		if (!ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
	},

	checkUpgradeInfo : function (firstRun){
		var t= Tabs.ThroneStuff;
		var countUpgrade = 0;
		var countEnhance = 0;
		var levelfrom = 0;
		var levelto =0;
		var qualityfrom = 0;
		var qualityto = 0;
		if (ThroneOptions.Items.length == 0) return;
		for (k=0;k<ThroneOptions.Items.length;k++){
			countUpgrade = 0;
			countEnhance = 0;
			if (uW.kocThroneItems[ThroneOptions.Items[k]["id"]] != undefined) {
				if (k>0) for (l=0;l<k;l++) {
					if (ThroneOptions.Items[l]["id"] == ThroneOptions.Items[k]["id"] && ThroneOptions.Items[l]["action"] == ""+culang.throneStuffUpgrade+"") {countUpgrade++;}
					if (ThroneOptions.Items[l]["id"] == ThroneOptions.Items[k]["id"] && ThroneOptions.Items[l]["action"] == ""+culang.throneStuffEnhance+"") {countEnhance++;}
				}
				if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffUpgrade+"") {
					ThroneOptions.Items[k]["levelfrom"] = parseInt(uW.kocThroneItems[ThroneOptions.Items[k]["id"]]["level"]) + countUpgrade;
					ThroneOptions.Items[k]["levelto"] = parseInt(ThroneOptions.Items[k]["levelfrom"]) +1;
					ThroneOptions.Items[k]["qualityfrom"] = parseInt(uW.kocThroneItems[ThroneOptions.Items[k]["id"]]["quality"]) + countEnhance;
					if (ThroneOptions.Items[k]["levelto"]>14 && !firstRun) {alert(""+culang.throneStuffEUQueueUpgradeLevel14+"");ThroneOptions.Items.splice (k,1);saveThroneOptions();return;}
				}
				if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffEnhance+"") {
					ThroneOptions.Items[k]["qualityfrom"] = parseInt(uW.kocThroneItems[ThroneOptions.Items[k]["id"]]["quality"]) + countEnhance;
					ThroneOptions.Items[k]["qualityto"] = parseInt(ThroneOptions.Items[k]["qualityfrom"]) +1;
					ThroneOptions.Items[k]["levelfrom"] = parseInt(uW.kocThroneItems[ThroneOptions.Items[k]["id"]]["level"]) + countUpgrade;
					if (ThroneOptions.Items[k]["qualityto"]>5 && !firstRun) {
						alert(""+culang.throneStuffEUQueueUpgradeQuality5+"");
						ThroneOptions.Items.splice (k,1);
						t.PaintQueue();
						t.paintInfo();
						saveThroneOptions();
						return;
					}
				}
				if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffEnhance+"") var lvl = parseInt(ThroneOptions.Items[k]["qualityfrom"]) +1;
				if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffUpgrade+"") var lvl = parseInt(ThroneOptions.Items[k]["levelfrom"]) +1;
				costAction = ThroneOptions.Items[k]["action"].toLowerCase();
				if (uW.cm.thronestats[costAction][lvl] != undefined) ThroneOptions.Items[k]["cost"] = uW.cm.thronestats[costAction][lvl].Stones;
				else ThroneOptions.Items.splice (k,1);
			} else ThroneOptions.Items.splice (k,1);
		}
		t.paintHoover();
		t.PaintQueue();
		t.paintInfo();
		saveThroneOptions();
	},

	PaintQueue : function (){
		var t= Tabs.ThroneStuff;
		if (ById('ShowQueueDiv')) ById('ShowQueueDiv').innerHTML = '<TABLE id=ShowQueue class=pdxStat align="center" width=90%></table>';
		for (k=(ThroneOptions.Items.length-1);k>=0;k--){
			if (typeof(uW.kocThroneItems[ThroneOptions.Items[k]["id"]]) == 'object') t._addTab(k,ThroneOptions.Items[k]["name"],ThroneOptions.Items[k]["qualityfrom"],ThroneOptions.Items[k]["qualityto"],ThroneOptions.Items[k]["levelfrom"],ThroneOptions.Items[k]["levelto"],ThroneOptions.Items[k]["action"],ThroneOptions.Items[k]["active"],ThroneOptions.Items[k]["cost"]);
			else ThroneOptions.Items.splice (k,1);
		}
		t._addTabHeader();
	},

	doAction : function (){
		var t= Tabs.ThroneStuff;
		var now = new Date().getTime()/1000.0;
		if (!ThroneOptions.Active) return;
		if (ThroneOptions.Items.length ==0) {
			if ( ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoItems+"</i>"
			return;
		}
		ThroneOptions.Items["0"]["active"] = true;
		t.PaintQueue();
		if (uW.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken == true && Seed.queue_throne.end == undefined){
			uW.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken = false;
			uW.kocThroneItems[ThroneOptions.Items["0"]["id"]].brokenType = "";
			setTimeout(t.doRepair,1000);
			clearTimeout(t.setActionTimer);
			t.setActionTimer = setInterval(t.doAction,5000);
			return;
		}
		if (uW.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken == false && Seed.queue_throne.end == undefined){
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDo+" " + ThroneOptions.Items["0"]["action"] + " "+culang.throneStuffEUQueueDo2+"</i>";
			if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffUpgrade+"") setTimeout(t.doUpgrade,2000);
			if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffEnhance+"") setTimeout(t.doEnhance,2000);
			clearTimeout(t.setActionTimer);
			t.setActionTimer = setInterval(t.doAction,5000);
		}
	},

	doEnhance : function() {
		var t = Tabs.ThroneStuff;
		if (typeof(uW.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'object') {
			var item = uW.kocThroneItems[ThroneOptions.Items["0"]["id"]];
		} else return;
		var cityid = 0;
		if (ThroneOptions.CityMax) {
			var max = 0;
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
					max = parseInt(Seed.resources["city"+k]["rec5"][0]);
					if (parseInt(Seed.resources["city"+k]["rec5"][0]) > 2*parseInt(ThroneOptions.Items["0"]["cost"])) {
						cityid = k;
					}
				}
			}
			
		} else {
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > 2*parseInt(ThroneOptions.Items["0"]["cost"]))	{
					cityid = k;
					break;
				}
			}
		}
		if(cityid == 0){
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoAetherstone+" "+ parseInt(Seed.resources["city"+k]["rec5"][0])+"</i>";
			// actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffEUQueueNoAetherstoneLog+" " + parseInt(Seed.resources["city"+k]["rec5"][0]) + " - "+culang.throneQualityUpgradeNote+" " + parseInt(ThroneOptions.Items["0"]["cost"])+" "+culang.throneQualityUpgradeNote2+"" );
			return;
		}
		var buffItemId = 0;
		if (ThroneOptions.i20004 && Seed.items.i20004 && parseInt(Seed.items.i20004) > 0) buffItemId = 20004;
		if (ThroneOptions.i20002 && Seed.items.i20002 && parseInt(Seed.items.i20002) > 0) buffItemId = 20002;
		if (ThroneOptions.i20003 && Seed.items.i20003 && parseInt(Seed.items.i20003) > 0) buffItemId = 20003;
		if (ThroneOptions.i20001 && Seed.items.i20001 && parseInt(Seed.items.i20001) > 0) buffItemId = 20001;
		if(buffItemId > 0){
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = culang.throneStuffItemUse+" <b>"+uW.itemlist['i'+buffItemId].name+"</b><br>";
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'upgradeQuality';
		params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
		params.buffItemId = buffItemId;
		params.payment = "aetherstone";
		params.cityId = cityid;
		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				var t = Tabs.ThroneStuff;
				if(rslt.ok){
					if (buffItemId > 0) {
						Seed.items['i'+buffItemId] = Seed.items['i'+buffItemId] - 1;
						if (Seed.items['i'+buffItemId] < 0) Seed.items['i'+buffItemId] = 0;
						uW.ksoItems[buffItemId].subtract();
					}
					if (rslt.gems > 0)
					{
						if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +'<i>'+culang.throneStuffSpendGems+'</i>';
						ThroneOptions.Active = false;
						saveThroneData();
					}
					Seed.resources["city" + cityid]["rec5"][0] -= rslt.aetherstones;
					item.level = rslt.item.level;
					item.quality = rslt.item.quality
					item.status = rslt.item.status;
					if (rslt.success){
						item.name = item.createName(); // ???
						ThroneOptions.Good++;
						ThroneOptions.Tries++;
						t.addToLog(ThroneOptions.Items["0"]["id"],ThroneOptions.Items["0"]["action"],ThroneOptions.Tries,ThroneOptions.Good,ThroneOptions.Bad);
						ThroneOptions.Tries = 0;
						ThroneOptions.Good = 0;
						ThroneOptions.Bad = 0;
						ThroneOptions.Items.splice (0,1);
						saveThroneOptions();
						var params = uW.Object.clone(uW.g_ajaxparams);
						params.emailTo = Seed.player['name'];
						params.subject = ''+culang.throneStuffERessourceMailSubject+' '+ getThroneItemName(item.id);
						var effft="",x=0,s = item;
						for (var u in s.effects) {
							L = s.effects[u];
							effect = uW.cm.thronestats.effects[L.id];
							var id = L.id;
							var tier = L.tier;
							p = false;
							while (!p && (tier > -1)) {
								p = uW.cm.thronestats.tiers[id][tier];
								tier--;
							}
							var base = p.base || 0;
							var growth = p.growth ||0;
												
							var percent = + base + (s.level * s.level + s.level) * + growth * 0.5;
							percent = percent > 0 ? "+" + percent : + percent;
							percent = Math.ceil(percent);
							effft += percent + "% " + effect[1] + " %0A";
						}
						params.message = effft;
						params.requestType = "COMPOSED_MAIL";;
						new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {method: "post",parameters: params,onSuccess: function (rslt) {

						},onFailure: function () {},});
						if (ById('ShowTries')) ById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTriesNone+"";
					}else{
						if (rslt['break']) {
							item.isBroken = true;
							item.brokenType = "quality";
						}
						item.quality = rslt.item.quality;
						item.level = rslt.item.level;
						item.status = rslt.item.status;
						item.name = item.createName(); 
						ThroneOptions.Tries++;
						ThroneOptions.Good++;
						if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +culang.throneStuffERStatusFaild+' <br /><span class="boldRed">'+culang.throneStuffERStatusFaild2+'</span> <u>' + uW.kocThroneItems[ThroneOptions.Items["0"]["id"]].name +"</u><br /><i>"+culang.throneStuffERStatusFaild3+"</i>";
						if (ById('ShowTries')) ById('ShowTries').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
					}
					uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
					t.checkUpgradeInfo(false);
					t.PaintQueue();
					saveThroneOptions();
				} else {
					// actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffRequestError+" "+ThroneOptions.Items["0"]["id"]+": " + transport.responseText);
					if(rslt.error_code==256) {

						/* setTimeout(function() {
						 reloadKOC();
						 },2000);

						 */
						item.isBroken = true;
						item.brokenType = "quality";
						item.name = item.createName(); 
						uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
						ThroneOptions.Tries++;
						saveThroneOptions();
						t.doRepair();

						return;
					}
					ThroneOptions.Bad++;
					saveThroneOptions();
				}
				return;
			},
			onFailure: function () {
				return;
			},
		});
	},

	doUpgrade : function() {
		var t = Tabs.ThroneStuff;
		if (typeof(uW.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'object') {
			var item = uW.kocThroneItems[ThroneOptions.Items["0"]["id"]];
		} else return;
		var cityid = 0;
		if (ThroneOptions.CityMax) {
			var max = 0;
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
					max = parseInt(Seed.resources["city"+k]["rec5"][0]);
					if (parseInt(Seed.resources["city"+k]["rec5"][0]) > 2*parseInt(ThroneOptions.Items["0"]["cost"])) {
						cityid = k;
					}
				}
			}
			
		} else {
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > 2*parseInt(ThroneOptions.Items["0"]["cost"]))	{
					cityid = k;
					break;
				}
			}
		}
		if(cityid == 0){
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoAetherstone+"</i>";
			return;
		}
		var buffItemId = 0;
		if (ThroneOptions.i20022 && Seed.items.i20022 && parseInt(Seed.items.i20022) > 0) buffItemId = 20022;
		if (ThroneOptions.i20019 && Seed.items.i20019 && parseInt(Seed.items.i20019) > 0) buffItemId = 20019;
		if (ThroneOptions.i20006 && Seed.items.i20006 && parseInt(Seed.items.i20006) > 0) buffItemId = 20006;
		if (ThroneOptions.i20005 && Seed.items.i20005 && parseInt(Seed.items.i20005) > 0) buffItemId = 20005;
		if (ThroneOptions.i20002 && Seed.items.i20002 && parseInt(Seed.items.i20002) > 0) buffItemId = 20002;
		if (ThroneOptions.i20001 && Seed.items.i20001 && parseInt(Seed.items.i20001) > 0) buffItemId = 20001;
		//Meistertoken
		if (item.level+1 == 3 && ThroneOptions.i20012 && Seed.items.i20012 && parseInt(Seed.items.i20012) > 0) buffItemId = 20012;
		if (item.level+1 == 5 && ThroneOptions.i20013 && Seed.items.i20013 && parseInt(Seed.items.i20013) > 0) buffItemId = 20013;
		if (item.level+1 == 7 && ThroneOptions.i20014 && Seed.items.i20014 && parseInt(Seed.items.i20014) > 0) buffItemId = 20014;
		if (item.level+1 == 9 && ThroneOptions.i20015 && Seed.items.i20015 && parseInt(Seed.items.i20015) > 0) buffItemId = 20015;
		if (item.level+1 == 10 && ThroneOptions.i20016 && Seed.items.i20016 && parseInt(Seed.items.i20016) > 0) buffItemId = 20016;
		if (item.level+1 == 11 && ThroneOptions.i20017 && Seed.items.i20017 && parseInt(Seed.items.i20017) > 0) buffItemId = 20017;
		if (item.level+1 == 12 && ThroneOptions.i20018 && Seed.items.i20018 && parseInt(Seed.items.i20018) > 0) buffItemId = 20018;
		if (item.level+1 == 13 && ThroneOptions.i20020 && Seed.items.i20020 && parseInt(Seed.items.i20020) > 0) buffItemId = 20020;
		if (item.level+1 == 14 && ThroneOptions.i20021 && Seed.items.i20021 && parseInt(Seed.items.i20021) > 0) buffItemId = 20021;
		if(buffItemId > 0){
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = culang.throneStuffItemUse+" <b>"+uW.itemlist['i'+buffItemId].name+"</b><br>";
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'upgradeLevel';
		params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
		params.buffItemId = buffItemId;
		params.payment = "aetherstone";
		params.cityId = cityid;
		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if(rslt.ok){
					if (buffItemId > 0) {
						Seed.items['i'+buffItemId] = parseInt(Seed.items['i'+buffItemId]) - 1;
						if (Seed.items['i'+buffItemId] < 0) Seed.items['i'+buffItemId] = 0;
						uW.ksoItems[buffItemId].subtract();
					}
					if (rslt.gems > 0)
					{
						if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +'<i>'+culang.throneStuffSpendGems+'</i>';
						ThroneOptions.Active = false;
						saveThroneData();
					}
					Seed.resources["city" +cityid]["rec5"][0] -= rslt.aetherstones;
					if (rslt.success)
					{
						item.level = rslt.item.level;
						ThroneOptions.Tries++;
					  ThroneOptions.Good++;
						item.quality = rslt.item.quality;
						item.name = item.createName(); // ???
						t.addToLog(ThroneOptions.Items["0"]["id"],ThroneOptions.Items["0"]["action"],ThroneOptions.Tries,ThroneOptions.Good,ThroneOptions.Bad);
						ThroneOptions.Tries = 0;
						ThroneOptions.Good = 0;
						ThroneOptions.Bad = 0;
						saveThroneOptions();

						ThroneOptions.Items.splice (0,1);
						var params = uW.Object.clone(uW.g_ajaxparams);
						params.emailTo = Seed.player['name'];
						params.subject = ''+culang.throneStuffURessourceMailSubject+' '+ getThroneItemName(item.id);
						var effft="";
						var x=0;
						s = item;
						for (var u in s.effects) {
							L = s.effects[u];
							effect = uW.cm.thronestats.effects[L.id];
							var id = L.id;
							var tier = L.tier;
							p = false;
							while (!p && (tier > -1)) {
								p = uW.cm.thronestats.tiers[id][tier];
								tier--;
							}
							var base = p.base || 0;
							var growth = p.growth ||0;
							var percent = + base + (s.level * s.level + s.level) * + growth * 0.5;
							percent = percent > 0 ? "+" + percent : + percent;
							percent = Math.ceil(percent);

							effft += percent + "% " + effect[1] + " %0A";

						}
						params.message = effft;
						params.requestType = "COMPOSED_MAIL";;
						new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
							method: "post",
							parameters: params,
							onSuccess: function (rslt) {

							},
							onFailure: function () {

							},
						});
						if (ById('ShowTries'))ById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTriesNone+"";
					}
					else
					{
						if (rslt['break']) {
							item.isBroken = true;
							item.brokenType = "level";
						}
						item.quality = rslt.item.quality;
						item.level = rslt.item.level;
						item.status = rslt.item.status;
						item.name = item.createName(); 
						ThroneOptions.Tries++;
						ThroneOptions.Good++;
						saveThroneOptions();
						if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +'<span class="boldRed">'+culang.throneStuffURStatusFaild+'</span><br />'+culang.throneStuffERStatusFaild2+' <u>' + getThroneItemName(ThroneOptions.Items["0"]["id"]) +"</u><br /><i>"+culang.throneStuffERStatusFaild3+"</i>";
						if (ById('ShowTries')) ById('ShowTries').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
					}
					uW.cm.ThroneView.renderInventory(uW.kocThroneItems);

					t.checkUpgradeInfo(false);
					t.PaintQueue();
					saveThroneOptions();
				} else {
					ThroneOptions.Bad++;
					saveThroneOptions();
				}
				return;
			},
			onFailure: function () {
				return;
			},
		});
	},

	doRepair : function() {
		var t = Tabs.ThroneStuff;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'timeRepair';
		params.throneRoomItemId = ThroneOptions.Items["0"]["id"];		
    new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
					if(rslt.ok){
              				ThroneOptions.RepairEnd = rslt.eta; 
              				var now = new Date().getTime()/1000.0;
              				var t = Tabs.ThroneStuff;
              				t.setRepairTimer = setInterval (t.repairTimerUpdate,1000); 
				 	 Seed.queue_throne.itemId= ThroneOptions.Items["0"]["id"];
		             		Seed.queue_throne.start=unixTime();
					 Seed.queue_throne.end= rslt.eta;
					 t.repairId = ThroneOptions.Items["0"]["id"];
					 t.repairEnd = rslt.eta;
					 uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
					 var x = rslt.eta - unixTime();
					//ThroneOptions.Good++;
					saveThroneOptions();
				   } else {	
				   		//ThroneOptions.Good++;
						saveThroneOptions();
				   }		
				   return;
			},
			onFailure: function () {
			   return;
			},
		});
	},

	doEquip : function(n,preset) {
		var t = Tabs.ThroneStuff;
		if (typeof(uW.kocThroneItems[n]) == 'object') {
			var y = uW.kocThroneItems[n];
		} else return;

		var params = uW.Object.clone(uW.g_ajaxparams);
		//logit(n.toSource());
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'equipItem';
		params.itemId = y.id;
		params.presetId = ById("preset").value;

		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if(rslt.ok){
					uW.cm.ThroneView.clickItemEquip(y);
					t.FillEquipCheckboxes();
				}
			},
			onFailure: function () {
				return;
			},
		});
	},

	doUnequip : function(n,preset) {
		var t = Tabs.ThroneStuff;
		if (typeof(uW.kocThroneItems[n]) == 'object') {
			var y = uW.kocThroneItems[n];
		} else return;

		var params = uW.Object.clone(uW.g_ajaxparams);
		//logit(n.toSource());
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'unequipItem';
		params.itemId = y.id;
		params.presetId = ById("preset").value;

		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if(rslt.ok){
					uW.cm.ThroneView.clickItemUnequip(y);
					t.FillEquipCheckboxes();
				}
			},
			onFailure: function () {
				return;
			},
		});
	},

	repairTimerUpdate :function (){
		var t = Tabs.ThroneStuff;
		if (ThroneOptions.Items.length == 0) return;
		var now = new Date().getTime()/1000.0;
		var diff = 0;
		if (Seed.queue_throne.end == undefined) return;
		else diff = Seed.queue_throne.end - now;
		if (diff <0){
			clearTimeout(t.setRepairTimer);
			if (ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueWaiting+"</i>";
			if (!ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
			uW.kocThroneItems[Seed.queue_throne.itemId].isBroken = false;
			Seed.queue_throne = "";
			return;
		} else {
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<b>"+culang.throneStuffRepairItem+"</b> " + getThroneItemName(ThroneOptions.Items["0"]["id"]) + "<br/><b>"+culang.throneStuffRepairTimeLeft+"</b> <span class='boldRed'>" + timestr(diff)+ " <sup>("+ timestr(Seed.queue_throne.end - Seed.queue_throne.start) + ")</sup></span>";
			if (ById('ShowTries')) ById('ShowTries').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
		}

	},

	paintInfo : function (){
		var t = Tabs.ThroneStuff;
		if (ThroneOptions.Items["0"]==undefined) ThroneOptions.Items=[];
		if (typeof(uW.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'number') {
			var y = uW.kocThroneItems[ThroneOptions.Items["0"]["id"]];
		} else return;
		var id =0;
		var tier=0;
		var Current=0;
		var Next=0;
		m="<TABLE width=80% height=0% align='center' class=pdxTab><TR><TD><B>"+culang.throneStuffItemCurrent+"</b></td><TD><B>"+culang.throneStuffItemNext+"</b></td>";
		for (i=1;i<=5;i++) {
			id = y["effects"]["slot"+i]["id"];
			tier = parseInt(y["effects"]["slot"+i]["tier"]);
			level = y["level"];
			p = false;
			while (!p && (tier > -1)) {
				p = uW.cm.thronestats.tiers[id][tier];
				tier--;
			}
   		var base = p.base || 0;
			var growth = p.growth ||0;
			Current = base + ((level * level + level) * growth * 0.5);
			level++;
			Next = base + ((level * level + level) * growth * 0.5);;
			var quality = parseInt(uW.kocThroneItems[ThroneOptions.Items["0"]["id"]]["quality"]);
			if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffEnhance+"") {
				if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td>';
				else m+='<TR><TD><FONT color=red>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td>';
				if (i<=(quality+1)) m+='<TD><FONT color=green>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
				else m+='<TD><FONT color=red>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			}
			if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffUpgrade+"") {
				if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td>';
				else m+='<TR><TD><FONT color=red>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td>';
				if (i<=quality) m+='<TD><FONT color=green>' + Next + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
				else m+='<TD><FONT color=red>' + Next + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			}
		}
		m+="</table>"
		document.getElementById('ShowInfo').innerHTML = m;

	},

	paintHoover : function (){
		var t = Tabs.ThroneStuff;
		if (!ById('ThroneItems')) return;
		var z = ById('ThroneItems').value;
		var y = uW.kocThroneItems[z];
		var id =0;
		var tier=0;
		var Current=0;
		//var imagesrc='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/'+faction+'/'+faction+'_'+type+'_normal_1.png'; 
		var imagesrc='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/'+y.faction+'/'+y.faction+'_'+y.type+'_normal_1_'+y.quality+'.png'; 
		m="<TABLE width=80% height=0% align='center' class=pdxTab><TR>";
		m+="<TD><TABLE class=pdxTab>";
		m+="<TR><TD><img src='"+imagesrc+"' height=30 width=30 /></td></tr>";
		m+="</TABLE>";
		m+="<td><TABLE>";
		for (i=1;i<=5;i++) {
			id = y["effects"]["slot"+i]["id"];
			tier = parseInt(y["effects"]["slot"+i]["tier"]);
			level = y["level"];
			p = false;
			while (!p && (tier > -1)) {
				p = uW.cm.thronestats.tiers[id][tier];
				tier--;
			}
			var base = p.base || 0;
			var growth = p.growth ||0;
			Current = base + ((level * level + level) * growth * 0.5);

			//if (ThroneOptions.Items["0"])
			// var quality = parseInt(uW.kocThroneItems[ThroneOptions.Items["0"]["id"]]["quality"]);
			//else
			var quality = y.quality
			if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
			else m+='<TR><TD><FONT color=red>' + Current + "% " + uW.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
		}
		m+="</table></td></tr></table>"
		ById('ShowHoover').innerHTML = m;

	},

	paintStones : function (){
		var t = Tabs.ThroneStuff;
		m="<TABLE width=90% height=0% class=pdxTab><TR><TD><img height=18 src='"+IMGastone30+"'></td>";
		for (i=0;i<Seed.cities.length;i++) m+='<TD>' + Seed.cities[i]["1"] + '</td>';
		m+="</tr><TR><TD></td>"
		for (i=0;i<Seed.cities.length;i++) m+='<TD>' + addCommas(Seed.resources["city"+Seed.cities[i]["0"]]["rec5"][0]) + '</td>';
		m+="</tr></table>"
		if (ById('ShowStones')) ById('ShowStones').innerHTML = m;
	},

	addToLog : function (id,action,tries,good,bad){
		var t = Tabs.ThroneStuff;
		var now = new Date();
		var time = now.getDate() +"/"+ (now.getMonth()+1) +"/"+ now.getFullYear() +"  "+ now.getUTCHours() + ":" + now.getMinutes();
		var name = getThroneItemName(id);
		t.log.push ({time:time,name:name,action:action,tries:tries,good:good,bad:bad});
		if (t.log.length > 50) t.log.splice(0,1);
		GM_setValue ('ThroneHistory_'+getServerId(), JSON2.stringify(t.log));
	},


	addToSalvageLog : function (msg,stones){
		var t = Tabs.ThroneStuff;
		var now = new Date();
		D = t.format00(now.getDate());
		M = t.format00(now.getMonth()+1);
		Y = t.format00(now.getFullYear());
		h = t.format00(now.getHours());
		m = t.format00(now.getMinutes());
		var time =  D +"/"+ M +"/"+ Y +"  "+ h + ":" + m;
		t.SalvageLog.push ({time:time,stones:stones,msg:msg});
		if (t.SalvageLog.length > 100) t.SalvageLog.splice(0,1);
		GM_setValue ('ThroneSalvageHistory_'+getServerId(), JSON2.stringify(t.SalvageLog));
	},

	addToSalvagePreviewList : function (number,msg,stones,isInFreeRow,del,keepReason){
		var t = Tabs.ThroneStuff;
		t.SalvagePreviewList.push ({number:number,isInFreeRow:isInFreeRow,stones:stones,msg:msg,del:del,keepReason:keepReason});
	},

	format00 : function (number) { if (number<10) number="0" + number; return number;},

	salvageCheck : function (){
		var t = Tabs.ThroneStuff;
		freeRowItems=(5*Seed.throne.rowNum);
		if(true) GM_log("salvageCheck()"
			+"\n\t"+"freeRows:"+Seed.throne.rowNum
			+"\n\t"+"freeRowItems:"+freeRowItems
		);

		var del = true;
		var keepReason="";
		var level = false;
		var type ="";
		var upgrading = false;
		var count=0;
		var salvageMsgs="";
		var effectIndex3;
		var effectIndex4; 
		var effectIndex5; 
		var countEffect;
		if(t.SalvagePreviewMode){
			t.SalvagePreviewList=[];
		} else {
			if(!Options.ThroneDeleteItems) { clearTimeout(t.timersalvage);return; }
			if (t.SalvageRunning == true) {
				return;
			}
			
			t.SalvageRunning = true;
		}

		for (m in uW.kocThroneItems) {
			var item = uW.kocThroneItems[m];
			// GM_log("item.id: "+item.id);
			if (typeof(item.id) != 'number') continue;
			count++;
			isInFreeRow = (count <= (parseInt(Seed.throne.rowNum) * 5));
			if (!(isInFreeRow || t.SalvagePreviewMode)) continue;

			del = true;
			keepReason = "";

			if (item.isEquipped || item.level > 0 || item.isBroken || item.id == t.LastDeleted) {
				del = false;
				keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonELB + "";
			}
			if (del) { // save first X items Filter
				if (count <= ThroneOptions.SalvageV2.SaveXitems) {
					del = false;
					keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonSaveFirst + " " + ThroneOptions.SalvageV2.SaveXitems + " " + culang.throneStuffSalvagePreviewKeepReasonSaveFirst2 + "";
				}
			}
			if (del) { // Upgrading Filter
				upgrading = false;
				for (k in ThroneOptions.Items) {
					if (ThroneOptions.Items[k]["id"] == item.id) upgrading = true;
				}
				if (upgrading) {
					del = false;
					keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonItemScheduled + "";
				}
			}
			if (del) { // Quality Filter
				if (ThroneOptions.SalvageV2.QualityFilter == 0) {
				}
				else if (item.quality >= ThroneOptions.SalvageV2.QualityFilter) {
					del = false;
					keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonQualityReached + "";
				}
			}
			if (del) { // Type Filter
				if (
					(item.type == "advisor" 			&& ThroneOptions.SalvageV2.TypeFilter.Advisor) ||
					(item.type == "banner"  			&& ThroneOptions.SalvageV2.TypeFilter.Banner ) ||
					(item.type == "chair"   			&& ThroneOptions.SalvageV2.TypeFilter.Chair  ) ||
					(item.type == "table"   			&& ThroneOptions.SalvageV2.TypeFilter.Table  ) ||
					(item.type == "window"  			&& ThroneOptions.SalvageV2.TypeFilter.Window ) ||
					(item.type == "trophy"  			&& ThroneOptions.SalvageV2.TypeFilter.Trophy ) ||
					(item.type == "candelabrum"  	&& ThroneOptions.SalvageV2.TypeFilter.Candelabrum) ||
					(item.type == "hero"  				&& ThroneOptions.SalvageV2.TypeFilter.Hero)
				) {
					del = false;
					keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonTypeMatching + " (" + item.type + ")";
				}
			}
			
			if (del) { //prepare effect filer
				var filter=ThroneOptions.SalvageV2.EffectFilter;
				var itemEffectPercent = [];
				var noneWithPercent=true;
				var nonChecked=true; var noneChecked1=true; var noneChecked2=true; var noneChecked3=true;
				for (i in uW.cm.thronestats.effects) {
					itemEffectPercent[i] = 0;
					if(typeof(filter[i])=='undefined') ThroneOptions.SalvageV2.EffectFilter[i]={IsEnabled:false,IsEnabled2:false,IsEnabled3:false,Value:''};
					if(typeof(filter[i].IsEnabled ) == "undefined" || filter[i].IsEnabled ===null) filter[i].IsEnabled =false;
					if(typeof(filter[i].IsEnabled2) == "undefined" || filter[i].IsEnabled2===null) filter[i].IsEnabled2=false;
					if(typeof(filter[i].IsEnabled3) == "undefined" || filter[i].IsEnabled3===null) filter[i].IsEnabled3=false;
					if(typeof(filter[i].Percent   ) == "undefined" || filter[i].Percent   ===null) filter[i].Percent   ='';
					if(filter[i].IsEnabled ) noneChecked1=false;
					if(filter[i].IsEnabled2) noneChecked2=false;
					if(filter[i].IsEnabled3) noneChecked3=false;
					if(filter[i].Percent!='') noneWithPercent=false;
				}
				noneChecked = noneChecked1 && noneChecked2 && noneChecked3;
				
				var effectMode1=ThroneOptions.SalvageV2.EffectMode;
				var effectMode2=ThroneOptions.SalvageV2.EffectMode2;
				var effectMode3=ThroneOptions.SalvageV2.EffectMode3;
				if(del && (effectMode1==100 || (effectMode1<100 && noneChecked1)) && (effectMode2==100 || (effectMode2==100 && noneChecked2)) && (effectMode3==100 || (effectMode3<100 && noneChecked3)) && noneWithPercent) {
					del=false; keepReason = "No effect selected"; //TODO multilang 
				} 
			}			
			
			if (del && !noneChecked1 && ThroneOptions.SalvageV2.EffectMode  <100) { // Effect Filter 1
				// 0 - mind. 1 von den letzten 3 Effekten
				// 2 - mind. 1 von den letzten 2 Effekten
				// 4 - mind. Letzter Effekt
				// 7 - mind. die letzten 2 Effekte
				// 8 - mind. die letzten 3 Effekte
				effectIndex3 = 0;
				effectIndex4 = 0;
				effectIndex5 = 0;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot3"].id].IsEnabled) effectIndex3 = 1;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot4"].id].IsEnabled) effectIndex4 = 3;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot5"].id].IsEnabled) effectIndex5 = 5;
				countEffect = effectIndex3 + effectIndex4 + effectIndex5;
				if (countEffect > ThroneOptions.SalvageV2.EffectMode) {
					del = false;
					keepReason = "Number of matching effects #A"; //TODO multilang
				}
			}
			if (del && !noneChecked2 && ThroneOptions.SalvageV2.EffectMode2 <100) { // Effect Filter 2
				// 0 - mind. 1 von den letzten 3 Effekten
				// 2 - mind. 1 von den letzten 2 Effekten
				// 4 - mind. Letzter Effekt
				// 7 - mind. die letzten 2 Effekte
				// 8 - mind. die letzten 3 Effekte
				effectIndex3 = 0;
				effectIndex4 = 0;
				effectIndex5 = 0;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot3"].id].IsEnabled2) effectIndex3 = 1;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot4"].id].IsEnabled2) effectIndex4 = 3;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot5"].id].IsEnabled2) effectIndex5 = 5;
				countEffect = effectIndex3 + effectIndex4 + effectIndex5;
				if (countEffect > ThroneOptions.SalvageV2.EffectMode2) {
					del = false;
					keepReason = "Number of matching effects #B"; //TODO multilang
				}
			}
			if (del && !noneChecked3 && ThroneOptions.SalvageV2.EffectMode3 <100) { // Effect Filter 3
				// 0 - mind. 1 von den letzten 3 Effekten
				// 2 - mind. 1 von den letzten 2 Effekten
				// 4 - mind. Letzter Effekt
				// 7 - mind. die letzten 2 Effekte
				// 8 - mind. die letzten 3 Effekte
				effectIndex3 = 0;
				effectIndex4 = 0;
				effectIndex5 = 0;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot3"].id].IsEnabled3) effectIndex3 = 1;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot4"].id].IsEnabled3) effectIndex4 = 3;
				if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot5"].id].IsEnabled3) effectIndex5 = 5;
				countEffect = effectIndex3 + effectIndex4 + effectIndex5;
				if (countEffect > ThroneOptions.SalvageV2.EffectMode3) {
					del = false;
					keepReason = "Number of matching effects #C"; //TODO multilang
				}
			}
			if (del) { // Effect Percent Filter
				// if(count==47) GM_log("item effects: "+item.effects["slot1"].id+","+item.effects["slot2"].id+","+item.effects["slot3"].id+","+item.effects["slot4"].id+","+item.effects["slot5"].id)	
				
				item_level = item.level;
				item_quality = item.quality;
				item_type = item.type;
				for (iEffect = 1; iEffect <= 5; iEffect++) {
					var id = item.effects["slot" + iEffect].id;
					var tier = parseInt(item.effects["slot" + iEffect].tier);
					p = false;
					while (!p && (tier > -1)) {
						p = uW.cm.thronestats.tiers[id][tier];
						tier--;
					}
					var base = p.base || 0;
					var growth = p.growth ||0;
					effect_value = base + ((item_level * item_level + item_level) * growth * 0.5);
					itemEffectPercent[id] += effect_value;
				}
				
				for (iEffect in uW.cm.thronestats.effects) {
					effect_name = uW.cm.thronestats.effects[iEffect]["1"];
					
					if(item_type=='advisor' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Advisor " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor)) {
							del = false;
							keepReason = keepReason = "Advisor " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}					
					}else if(item_type=='banner' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Banner " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner)) {
							del = false;
							keepReason = keepReason = "Banner " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}		
					}else if(item_type=='chair' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Chair " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair)) {
							del = false;
							keepReason = keepReason = "Chair " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}
					}else if(item_type=='table' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Table " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable)) {
							del = false;
							keepReason = keepReason = "Table " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}	
					}else if(item_type=='window' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Window " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow)) {
							del = false;
							keepReason = keepReason = "Window " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}	
					}else if(item_type=='trophy' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Trophy " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy)) {
							del = false;
							keepReason = keepReason = "Trophy " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}	
					}else if(item_type=='candelabrum' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Candelabrum " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum)) {
							del = false;
							keepReason = keepReason = "Candelabrum " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}	
					} else if(item_type=='hero' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentHero != ''){
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentHero) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = "Hero " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentHero + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentHero)) {
							del = false;
							keepReason = keepReason = "Hero " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentHero + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}	
					}
					if (del && ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent != '') {
						// GM_log("EffectPercentFilter "+ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent +" =? "+itemEffectPercent[iEffect] +" ==0? "+(ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent == 0)+ " "+(Math.abs(itemEffectPercent[iEffect]) > 0.0));
						if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent) == 0.0) {
							if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
								del = false;
								keepReason = ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
								break;
							}
						} else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent)) {
							del = false;
							keepReason = ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
							break;
						}
					}
				}
			}
			if (false) { // KSX DRAFT "ThroneItemDeleteFilter" (no configuration UI)
				var effectCount = [];
				for (i in uW.cm.thronestats.effects) effectCount[i] = 0;
				for (i = 1; i <= 5; i++) effectCount[item.effects["slot" + i].id] += 1;

				if (effectCount[ 1] + effectCount[18] >= 4) del = false; // Attack + Defense Debuff
				if (effectCount[ 2] + effectCount[17] >= 4) del = false; // Defense + Attack Debuff
				if (effectCount[91] + effectCount[93] >= 2) del = false; // Chance to Find Items + Chance to Find Items in PvP
				if (effectCount[25] + effectCount[26] >= 3) del = false; // Infantry Defense + Infantry Life
				if (effectCount[ 1] >= 4) del = false; // Attack								| A
				if (effectCount[ 2] >= 4) del = false; // Defense							|   D
				if (effectCount[ 4] >= 3) del = false; // Combat Speed
				if (effectCount[ 5] >= 2) del = false; // Range								| A D
				if (effectCount[ 6] >= 3) del = false; // Load								| A    *
				if (effectCount[16] >= 2) del = false; // Bonus to Wall
				if (effectCount[17] >= 4) del = false; // Attack Debuff						|   D
				if (effectCount[18] >= 4) del = false; // Defense Debuff						| A
				if (effectCount[20] >= 2) del = false; // Combat Speed Debuff
				if (effectCount[21] >= 2) del = false; // Range Debuff						| A D
				if (effectCount[25] >= 2) del = false; // Infantry Defense					|   D
				if (effectCount[26] >= 2) del = false; // Infantry Life						| A D
				if (effectCount[34] >= 2) del = false; // Ranged Attack						| A
				if (effectCount[37] >= 2) del = false; // Ranged Range						| A
				if (effectCount[45] >= 2) del = false; // Horsed Defense						|   D
				if (effectCount[46] >= 2) del = false; // Horsed Life						| A D
				if (effectCount[58] >= 2) del = false; // Siege Range						| A D
				if (effectCount[59] >= 2) del = false; // Siege Load							| A   *
				if (effectCount[68] >= 1) del = false; // Attack March Speed					| A
				if (effectCount[77] >= 2) del = false; // Troop Training Speed				|     *
				if (effectCount[91] >= 2) del = false; // Chance to Find Items				| A   *
				if (effectCount[92] >= 2) del = false; // Chance to Find Items in Dark Forests     *
				if (effectCount[93] >= 2) del = false; // Chance to Find Items in PvP		| A   *

			}

			if(!del && ThroneOptions.SalvageV2.DeleteXitems.IsEnabled &&
				count>freeRowItems-parseIntNan(ThroneOptions.SalvageV2.DeleteXitems.Value) &&
				isInFreeRow
				){
				del = true;keepReason="Delete last "+ThroneOptions.SalvageV2.DeleteXitems.Value+" items";
			}

			if (t.SalvagePreviewMode) {
				if (del) {
					var effects = uW.cm.thronestats.effects;
					var msg = (getThroneItemName(item.id) + " (" + effects[item.effects["slot1"].id]["1"] + "/" + effects[item.effects["slot2"].id]["1"] + "/" + effects[item.effects["slot3"].id]["1"] + "/" + effects[item.effects["slot4"].id]["1"] + "/" + effects[item.effects["slot5"].id]["1"] + ")");
					//salvageMsgs+=msg+"\n";
					if (false) GM_log(count + " DELETE: " + msg);
					t.addToSalvagePreviewList(count, msg, -1, isInFreeRow, del, keepReason);
				} else if (true) { //DEBUG ONLY
					var effects = uW.cm.thronestats.effects;
					var msg = (getThroneItemName(item.id) + " (" + effects[item.effects["slot1"].id]["1"] + "/" + effects[item.effects["slot2"].id]["1"] + "/" + effects[item.effects["slot3"].id]["1"] + "/" + effects[item.effects["slot4"].id]["1"] + "/" + effects[item.effects["slot5"].id]["1"] + ")");
					//salvageMsgs+=msg+"\n";
					if (false) GM_log(count + " KEEP: " + msg);
					t.addToSalvagePreviewList(count, msg, -1, isInFreeRow, del, keepReason);
				}
			} else {
				if (del) {
					t.SalvageArray.push(item.id);
				}
			}
		}

		//if(true){GM_log("Items to delete:\n"+salvageMsgs);}

		if(t.SalvagePreviewMode){
			t.PaintSalvagePreview();
		} else {
			if (t.SalvageArray.length == 0) {
				t.SalvageRunning = false;
				actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffNoItemToDelete+" "+ThroneOptions.IntervalMin+" "+culang.throneStuffNoItemToDelete2+"");
				t.timersalvage = setTimeout(t.salvageCheck,ThroneOptions.IntervalMin*60*1000);
			} else {
				actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffSalvageStart+" "+t.SalvageArray.length+" "+culang.throneStuffSalvageStart2+"");
				setTimeout(t.doSalvage, 2000);
			}
		}

	},

	doSalvage : function(){
		var t = Tabs.ThroneStuff;
		if(!Options.ThroneDeleteItems) { clearTimeout(t.timersalvage);return; }
		//Soll es erst auf Level 1?
		//Sind genug Aethersteine da?
		var cost = uW.cm.thronestats["upgrade"][1].Stones;
		var cityid = 0;
		if (ThroneOptions.CityMax) {
			var max = 0;
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
					max = parseInt(Seed.resources["city"+k]["rec5"][0]);
					if (parseInt(Seed.resources["city"+k]["rec5"][0]) > cost) {
						cityid = k;
					}
				}
			}
			
		} else {
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > cost)	{
					cityid = k;
					break;
				}
			}
		}

		if (ThroneOptions.SalvageV2.LevelP1 && cityid > 0) {
			t.doUpgradeNew();
		} else {
			t.doSalvageNew();
		}
	},	
		
	doUpgradeNew: function() {
		var t = Tabs.ThroneStuff;
		var itemID = t.SalvageArray[0];
		var cost = uW.cm.thronestats["upgrade"][1].Stones;
		var cityid = 0;
		if (ThroneOptions.CityMax) {
			var max = 0;
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
					max = parseInt(Seed.resources["city"+k]["rec5"][0]);
					if (parseInt(Seed.resources["city"+k]["rec5"][0]) > cost) {
						cityid = k;
					}
				}
			}
			
		} else {
			for (var k in Cities.byID) {
				if (parseInt(Seed.resources["city"+k]["rec5"][0]) > cost)	{
					cityid = k;
					break;
				}
			}
		}
		if(cityid == 0){
			//in keiner Stadt sind genug Aethersteine vorhanden
			if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoAetherstone+"</i>";
			return;
		}

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'upgradeLevel';
		params.throneRoomItemId = itemID;
		params.buffItemId = 0;
		params.payment = "aetherstone";
		params.cityId = cityid;
		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if(rslt.ok){
					if (rslt.gems > 0){
						//Edelsteine wurden verwendet
						
					}
					Seed.resources["city" +cityid]["rec5"][0] -= rslt.aetherstones;
					if (rslt.success) {
						//war ok
						var item =  uW.kocThroneItems[params.throneRoomItemId];
						item.level = rslt.item.level;
						item.quality = rslt.item.quality;
						item.name = item.createName(); 
						uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
						ThroneOptions.delItem = itemID;
						saveThroneOptions();
						setTimeout(t.doSalvageNew, 500);
						return;
					} else {
						//hat nicht geklappt
						var item =  uW.kocThroneItems[params.throneRoomItemId];
						item.isBroken = true;
						item.brokenType = "level";
						item.status = rslt.item.status;
						item.name = item.createName(); 
						t.SalvageArray.splice(0,1);
						uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
					}
				} else {
					//Fehler
					t.SalvageArray.splice(0,1);
				}
				if (t.SalvageArray.length > 0) {
					setTimeout(t.doSalvage, 5000);
				} else {
					t.SalvageRunning = false;
					t.salvageCheck();
				}
				return;
			},
			onFailure: function () {
				//Schwerer Fehler
				t.SalvageArray.splice(0,1);
				if (t.SalvageArray.length > 0) {
					setTimeout(t.doSalvage, 5000);
				} else {
					t.SalvageRunning = false;
					t.salvageCheck();
				}
				return;
			},
		});
	},
		
	doSalvageNew: function() {
		var t = Tabs.ThroneStuff;
		var cityid = 0;
		if (ThroneOptions.SalvageV2.CityMin) {
			var min = 99999999;
			for (var i in Cities.byID) {
				if (parseInt(Seed.resources["city"+i]["rec5"][0]) < min) {
					min = parseInt(Seed.resources["city"+i]["rec5"][0]);
					cityid = i;
				}
			}
		} else {
			for (var i in Cities.byID) {
				if (parseInt(Seed.resources["city"+i]["rec5"][0]) < 1950000) {
					cityid = i;
					break;
				}
			}
			if (cityid == 0) {
				//Keine Stadt hat weniger als 1950k Aether. Es wird die 1. Stadt verwendet
				cityid = Seed.cities[0][0];
			}
		}
		if (ThroneOptions.delItem > 0 ) var item = ThroneOptions.delItem;
			else var item = t.SalvageArray[0];
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'salvage';
		params.itemId = item;
		params.cityId = cityid;
		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				try{
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
					if(rslt.ok){
						var item =  uW.kocThroneItems[params.itemId];
						var effects = uW.cm.thronestats.effects;
						var msg = (getThroneItemName(item.id) + " (" + effects[item.effects["slot1"].id]["1"] + "/"+ effects[item.effects["slot2"].id]["1"]+ "/"+ effects[item.effects["slot3"].id]["1"]+ "/"+ effects[item.effects["slot4"].id]["1"]+ "/"+ effects[item.effects["slot5"].id]["1"] +")");
						t.addToSalvageLog(msg,rslt.aetherstones);
						uW.kocThroneItems[params.itemId].salvage();
						ThroneOptions.delItem = 0;
						saveThroneOptions();
					}
					else {
						t.addToSalvageLog(""+culang.throneStuffSalvageFaild+"",0);
						ThroneOptions.delItem = 0;
						saveThroneOptions();
					}
				} catch(err){
					t.addToSalvageLog(""+culang.throneStuffSalvageFaild+"",0);
					ThroneOptions.delItem = 0;
					saveThroneOptions();
				}
			},
			onFailure: function () {
				t.addToSalvageLog(""+culang.throneStuffSalvageFaild+"",0);
				ThroneOptions.delItem = 0;
				saveThroneOptions();
				return;
			},
		});
		t.SalvageArray.splice(0,1);
		t.LastDeleted = params.itemId;
		if (t.SalvageArray.length > 0) {
			setTimeout(t.doSalvage, 5000);
		} else {
			t.SalvageRunning = false;
			t.salvageCheck();
		}
	},
	


	
	hide : function (){
	},

	show : function (){
		var t = Tabs.ThroneStuff;
		if (t.curTabName == 'Sal')
			t.Salvage();
		else if (t.curTabName == 'UE')
			t.Upgrade_Enhance();
		else if (t.curTabName == 'RE')
			t.autorepair();
		else if (t.curTabName == 'ST')
			t.Stats();
		else if (t.curTabName == 'EQ') {
			t.Equip();
			for (k in t.EquipType) {
				var y = t.EquipType[k];
				if (typeof(y) == "string") {
					what = y.toLowerCase();
					t.paintEquipInfo(document.getElementById(what).value,what)
				}
			}
		}
	},
	autorepair:function() {
		var t = Tabs.ThroneStuff;
		var  m= '<DIV class=pdxStat>'+culang.throneStuffRepairHead+'</div><TABLE class=pdxTab width=750><tr><td></table><TABLE class=pdxTab width=98%><TR>';
		if (Options.salvageconfig.Repairrunning == true) {
			m += '<TD><INPUT id=KsTroneRepairEnable type=submit value="'+culang.throneStuffRepair+' = '+culang.buttonON+'"></td>';
		}
		else {
			m += '<TD><INPUT id=KsTroneRepairEnable type=submit value="'+culang.throneStuffRepair+' = '+culang.buttonOFF+'"></td>';
		}

		m+='<td><i>'+culang.throneStuffRepairAll+'<bR><font color=red>'+culang.throneStuffRepairAll2+'</font></i></td><tr></table>';


		t.Overv.innerHTML = m;

		ById('KsTroneRepairEnable').addEventListener ('click', function(){t.toggleRepairon(this);}, false);
	},
	toggleRepairon: function(obj){
		if (ThroneOptions.Active) {
			alert(culang.throneStuffUERunningNotPossible);
			return;
		}
		var t = Tabs.ThroneStuff;
		obj = ById('KsTroneRepairEnable');
		if (Options.salvageconfig.Repairrunning == true) {
			Options.salvageconfig.Repairrunning = false;
			if (obj) obj.value = culang.throneStuffRepair+' = '+culang.buttonOFF;
		}
		else {
			Options.salvageconfig.Repairrunning = true;
			if (obj) obj.value = culang.throneStuffRepair+' = '+culang.buttonON;

			RepairAuto.init();
		}
		saveOptions ();
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Farm.js">
//	
//	   KOC POWER - TABS FARM											        
//	


Tabs.farm = {
	tabLabel: culang.tabLabelAutoFarm,
	tabOrder : TabOptions.toFarm,
	myDiv : null,
	MapAjax : new CMapAjax(),
	popFirst : true,
	opt : {},
	// nextattack : null,
	updateSeedTimer: null,
	tilesSearched : 0,
	tilesFound : 0,
	helpArray:{},
	FarmArray:{},
	marchArray:[],
	lookup:1,
	city:0,
	deleting:false,
	mapblocks: [],
	mapDat: [],
	DipArray: ["friendly","hostile","friendlyToThem","friendlyToYou","neutral","unallied"],
	interval: ["Continuously","1 Hour","2 Hours","3 Hours","6 Hours","12 Hours","24 Hours"],

  	init : function (div){
	    var t = Tabs.farm;
	    t.myDiv = div;

	    var m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.farmHead+'</div><TABLE id=pbbarbingfunctions width=100% height=0% class=pdxTab><TR align="center">';
			if (FarmOptions.Running == false) {
			m += '<TD><INPUT id=FarmAttSearch type=submit value="'+culang.farmButton+' = '+culang.buttonOFF+'"></td>';
		} else {
			m += '<TD><INPUT id=FarmAttSearch type=submit value="'+culang.farmButton+' = '+culang.buttonON+'"></td>';
		}
	    m +='<TD><INPUT id=pbpaintFarms type=submit class=pbButton class=pbButton value="'+culang.farmShow+'">';
	    m += '<SELECT id=pbFarmcity type=list></select></td><TD><INPUT id=FarmSearch type=submit class=pbButton class=pbButton value="'+culang.farmSearch+'"></td><TD><DIV id=FarmSearchPR></div></td></tr></table>';
	    m += '</tr></table></div>';
	    m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.farmHeadStats+'</div>';
	    m += '<TABLE id=pbfarmstats width=95% height=0% class=pdxTab><TR align="left"><TR>';
	    for(i=0;i<Seed.cities.length;i++) m += '<TD>' + Seed.cities[i][1] +'</td>'; 
	    m+='</tr><TR>';
	    for(i=0;i<Seed.cities.length;i++) m += '<TD><DIV><span id='+ 'pdtotalFarm' + i +'></span></div></td>';
	    m+='</tr><TR>';
	    for(i=0;i<Seed.cities.length;i++) m += '<TD><DIV><span id='+ 'pddataFarm' + i +'></span></div></td>';    
	    m+='</tr><TR>'
	    for(i=0;i<Seed.cities.length;i++) m += '<TD><DIV><span id='+ 'pddataFarmarray' + i +'></span></div></td>'; 
	    m+='</tr></table>';    
	    m+='<DIV id=FarmCheck></div>';
	    m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.farmHeadOptions+'</div>';
	    m += '<TABLE id=pbfarmstats width=90% height=0% class=pdxTab>';
	    m += '<TR><TD>'+culang.farmIntervall+'</td><TD><SELECT id=FarmInterval type=list></td></tr>';
	    m += '<TR><TD>'+culang.farmDeleteRpt+'</td><TD><INPUT id=FarmReports type=checkbox '+(FarmOptions.DeleteReports?'CHECKED':'')+'></td><tr>';
	    m += '<TR><TD>'+uW.g_js_strings.commonstr.might+':</td>';
	    m += '<TD width=50>'+culang.shortMin+':<INPUT type=text id=FarmMinMight size=11 maxlength=11 value='+ FarmOptions.MinMight +'></td>';
	    m += '<TD>'+culang.shortMax+':<INPUT type=text id=FarmMaxMight size=11 maxlength=11 value='+ FarmOptions.MaxMight +'></td></tr>';
	    m += '<TR><TD>'+culang.farmInactivePlayer+' </td>';
	    m += '<TD><INPUT type=text id=FarmInactive size=3 value='+ FarmOptions.Inactive +'> '+culang.farmInactivePlayer2+'</td></table>';
	    m += '<TABLE id=pbfarmstats width=90% height=0% class=pdxTab><TR align="left"><TR><TD width=100>'+uW.g_js_strings.commonstr.city+':</td>';
	    for (i=1;i<=Seed.cities.length;i++) m+='<TD class=pbCityEn><INPUT id=CityEnable'+ i +'  type=checkbox '+(FarmOptions.CityEnable[i]?'CHECKED':'')+'>'+ Seed.cities[i-1][1] +'</td>';  
	    m += '</tr></table><TABLE id=pbfarmstats width=90% height=0% class=pdxTab><TR align="left"><TD width=100>'+culang.farmCityLevel+'</td>';
	    for (i=1;i<=12;i++) m+='<TD class=pbCityOpt><INPUT id=CityLevel'+ i +'  type=checkbox '+(FarmOptions.CityLevel[i]?'CHECKED':'')+'>'+ i +'</td>'; 
	    m += '</tr></table><TABLE id=pbfarmstats width=90% height=0% class=pdxTab><TR align="left"><TR><TD width=100>'+culang.farmDip+'</td>';
	    for (i=0;i<t.DipArray.length;i++) m+='<TD class=pbDipOpt><INPUT id=Diplomacy'+ t.DipArray[i] +'  type=checkbox '+(FarmOptions.Diplomacy[t.DipArray[i]]?'CHECKED':'')+'>'+ t.DipArray[i] +'</td>';    
	    m+='</tr></table>';   
	    m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.farmHeadTroops+'</div>';
	    m += '<TABLE id=pbaddreasignroute width=100% height=0% class=pdxTab><TR align="center">';
	    m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_1_50.jpg"></td>';
	    m += '<TD>'+culang.supplytroop+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_2_50.jpg"></td>'
	    m += '<TD>'+culang.militiaman+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_3_50.jpg"></td>'
	    m += '<TD>'+culang.scout+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_4_50.jpg"></td>'
	    m += '<TD>'+culang.pikeman+'</td></tr>'
	    m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop1  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[1] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop2  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[2] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop3  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[3] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop4  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[4] +'\></td></tr>';
	    m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_5_50.jpg"></td>';
	    m += '<TD>'+culang.swordsman+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_6_50.jpg"></td>'
	    m += '<TD>'+culang.archer+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_7_50.jpg"></td>'
	    m += '<TD>'+culang.cavalry+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_8_50.jpg"></td>'
	    m += '<TD>'+culang.heavycavalry+'</td></tr>'
	    m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop5  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[5] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop6  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[6] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop7  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[7] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop8  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[8] +'\></td></tr>';
	    m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_9_50.jpg"></td>';
	    m += '<TD>'+culang.supplywagon+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_10_50.jpg"></td>'
	    m += '<TD>'+culang.ballista+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_11_50.jpg"></td>'
	    m += '<TD>'+culang.batteringram+'</td>'
	    m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_12_50.jpg"></td>'
	    m += '<TD>'+culang.catapult+'</td></tr>'
	    m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop9  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[9] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop10  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[10] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop11  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[11] +'\></td>';
	    m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop12 type=text size=10 maxlength=10 value='+ FarmOptions.Troops[12] +'\></td></tr></table>';
	    
	    t.myDiv.innerHTML = m;
	     
	    t.checkFarmData();
	    document.getElementById('pbFarmcity').options.length=0;
	    for (i=0;i<Seed.cities.length;i++){
	        var o = document.createElement("option");
	        o.text = Seed.cities[i][1]
	        o.value = i+1;
	        document.getElementById("pbFarmcity").options.add(o);
		}
	    document.getElementById('FarmInterval').options.length=0;
	    for (i=0;i<t.interval.length;i++){
	        var o = document.createElement("option");
	        o.text = t.interval[i];
	        o.value = i;
	        document.getElementById("FarmInterval").options.add(o);
		}
	    document.getElementById('FarmInterval').value = FarmOptions.Interval;    
	    for(i=0;i<Seed.cities.length;i++){
	            var elem = 'pdtotalFarm'+i;
	            if (t.FarmArray[i+1] == undefined) document.getElementById(elem).innerHTML = '<i>'+culang.farmNoData+'</i>';
	            else document.getElementById(elem).innerHTML =  ''+culang.farmFarms+' ' + t.FarmArray[i+1].length +'/'+ t.helpArray[i+1].length;
	    }
	    document.getElementById('FarmInterval').addEventListener('change', function(){FarmOptions.Interval = document.getElementById('FarmInterval').value;saveFarmOptions();} , false);
	    document.getElementById('FarmReports').addEventListener('change', function(){FarmOptions.DeleteReports = document.getElementById('FarmReports').checked;saveFarmOptions();} , false);
	    document.getElementById('FarmAttSearch').addEventListener('click', function(){t.toggleBarbState(this)} , false);
	    document.getElementById('FarmSearch').addEventListener('click', function(){
	        for (i=1;i<=Seed.cities.length;i++) GM_deleteValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId());
	        for(i=0;i<Seed.cities.length;i++){
	                var elem = 'pdtotalFarm'+i;
	                document.getElementById(elem).innerHTML = '<i>'+culang.farmNoData+'</i>';
	        }
	        t.checkFarmData();
	    } , false);
	    document.getElementById('pbpaintFarms').addEventListener('click', function(){t.showFarms(document.getElementById("pbFarmcity").value,Seed.cities[document.getElementById("pbFarmcity").value -1][1]);},false);   
	    document.getElementById('FarmMinMight').addEventListener('change', function(){FarmOptions.MinMight = parseInt(document.getElementById('FarmMinMight').value);t.FilterFarms();saveFarmOptions();} , false);
	    document.getElementById('FarmMaxMight').addEventListener('change', function(){FarmOptions.MaxMight = parseInt(document.getElementById('FarmMaxMight').value);t.FilterFarms();saveFarmOptions();} , false);
	    document.getElementById('FarmInactive').addEventListener('change', function(){FarmOptions.Inactive = parseInt(document.getElementById('FarmInactive').value);t.FilterFarms();saveFarmOptions();} , false);
	  
	    var element = document.getElementsByClassName('pbTroopOpt');
	    for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=1;i<=10;i++){
                    FarmOptions.Troops[i] = document.getElementById('FarmTroop' + i).value;
                    saveFarmOptions();
                }
            }, false);
	    }
	    
	    element = document.getElementsByClassName('pbCityOpt');
	    for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=1;i<=12;i++){
                    FarmOptions.CityLevel[i] = document.getElementById('CityLevel' + i).checked;
                    saveFarmOptions();
                }
                t.FilterFarms();
            }, false);
	     }
	    
	    element = document.getElementsByClassName('pbCityEn');
	    for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=1;i<=Seed.cities.length;i++){
                    FarmOptions.CityEnable[i] = document.getElementById('CityEnable' + i).checked;
                    saveFarmOptions();
                }
                t.checkFarmData();
                t.FilterFarms();
            }, false);
	    }
    
	    element = document.getElementsByClassName('pbDipOpt');
	    for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=0;i<t.DipArray.length;i++){
                    FarmOptions.Diplomacy[t.DipArray[i]] = document.getElementById('Diplomacy' + t.DipArray[i]).checked;
                    saveFarmOptions();
                }
                t.FilterFarms();
            }, false);
	      
	    }
   	},
   
    showFarms: function (citynumber,cityname) {
        var t = Tabs.farm;
        var popTradeRoutes = null;
        t.popTradeRoutes = new CPopup('pbShowFarms', 0, 0, 1100, 485, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';       
        t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv().innerHTML = '<div class="popupBanner">'+cityname+' '+culang.farmFarms+'</div>';
        t.paintFarms(citynumber,cityname);
        t._addTabHeader(citynumber,cityname);
        t.popTradeRoutes.show(true)    ;
    },
    
    ToggleFarms: function(citynumber) {
        var t = Tabs.farm;
        var id=0;
        var element_class = document.getElementsByClassName('Farm');
               for (d = 1; d <= t.FarmArray[citynumber].length; d++) {
                    id = d-1;
                    var ele = document.getElementById('FarmToggle' + d);
              if (ele.checked) {
            t.FarmArray[citynumber][id].enabled = true;
            t.FarmArray[citynumber][id].lost = false;
            t.FarmArray[citynumber][id].empty = 0;   
        }
                    else t.FarmArray[citynumber][id].enabled = false;
            }
        for (i=0;i<t.helpArray[citynumber].length;i++){
                for (j=0;j<t.FarmArray[citynumber].length;j++){
                     if (parseInt(t.FarmArray[citynumber][j]['x']) == parseInt(t.helpArray[citynumber][i]['x']) && parseInt(t.FarmArray[citynumber][j]['y']) == parseInt(t.helpArray[citynumber][i]['y'])) t.helpArray[citynumber][i].enabled = t.FarmArray[citynumber][j].enabled;
                }
        }
        GM_setValue('Farms_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(t.helpArray[citynumber]));
    },
        
    paintFarms: function(i,cityname){
        var t = Tabs.farm;
        for (k=(t.FarmArray[i].length-1);k>=0;k--){t._addTab(i,cityname,k+1,t.FarmArray[i][k]['enabled'], t.FarmArray[i][k]['x'], t.FarmArray[i][k]['y'],t.FarmArray[i][k]['dist'], t.FarmArray[i][k]['level'],t.FarmArray[i][k]['AllianceName'], t.FarmArray[i][k]['Diplomacy'], t.FarmArray[i][k]['PlayerName'], t.FarmArray[i][k]['cityName'],t.FarmArray[i][k]['might'], t.FarmArray[i][k]['cityNumber'], t.FarmArray[i][k]['attacked'],t.FarmArray[i][k]['DaysInactive'],t.FarmArray[i][k]['lost'],t.FarmArray[i][k]['empty'],t.FarmArray[i][k]['gold'],t.FarmArray[i][k]['resource1'],t.FarmArray[i][k]['resource2'],t.FarmArray[i][k]['resource3'],t.FarmArray[i][k]['resource4']);}
    },


	_addTab: function(citynumber,cityname,queueId,status,X,Y,dist,level,AllianceName,diplomacy,playerName,cityName,might,cityNumber,attacked,DaysInactive,lost,empty,gold,rec1,rec2,rec3,rec4){
	    var t = Tabs.farm;
	    var row = document.getElementById('pbBars').insertRow(0);
	    row.vAlign = 'top';     
	    if (lost) row.style.color = "red";
	    if (!lost && empty == 0) row.style.color = "black";
	    if (FarmOptions.Inactive > DaysInactive) row.style.color = "orange";
	    row.insertCell(0).innerHTML = queueId;
	    row.insertCell(1).innerHTML = '<a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ X +',' +Y+ ')</a>';
	    row.insertCell(2).innerHTML = dist;
		row.insertCell(3).innerHTML = level;
		row.insertCell(4).innerHTML = AllianceName;
		row.insertCell(5).innerHTML = diplomacy;    
		row.insertCell(6).innerHTML = playerName;
		row.insertCell(7).innerHTML = cityName;
		row.insertCell(8).innerHTML = addCommas(might);
		row.insertCell(9).innerHTML = DaysInactive;
		row.insertCell(10).innerHTML = attacked;
	    row.insertCell(11).innerHTML = '<INPUT class=Farm id="FarmToggle' + queueId + '" type=checkbox>';    
	    var element_class = document.getElementsByClassName('Farm');
		for (c = 0; c < element_class.length; c++) {
            element_class[c].checked = t.FarmArray[citynumber][c].enabled;
            element_class[c].addEventListener('click', function(){t.ToggleFarms(citynumber)}, false);
		}
	},
        
    _addTabHeader: function(citynumber,cityname) {
        var t = Tabs.farm;
	    var row = document.getElementById('pbBars').insertRow(0);
	    row.vAlign = 'top';
	    row.insertCell(0).innerHTML = "<b><u>"+culang.farmId+"</u></b>";
	    row.insertCell(1).innerHTML = "<b><u>"+culang.shortCoordinate+"</u></b>";
	    row.insertCell(2).innerHTML = "<b><u>"+culang.shortDistance+"</u></b>";
	    row.insertCell(3).innerHTML = "<b><u>"+uW.g_js_strings.commonstr.level+"</u></b>";
	    row.insertCell(4).innerHTML = "<b><u>"+culang.farmAllianceName+"</u></b>";
	    row.insertCell(5).innerHTML = "<b><u>"+culang.mainDiplo+"</u></b>";
	    row.insertCell(6).innerHTML = "<b><u>"+culang.farmPlayerName+"</u></b>";
	    row.insertCell(7).innerHTML = "<b><u>"+culang.farmCityName+"</u></b>";
	    row.insertCell(8).innerHTML = "<b><u>"+uW.g_js_strings.commonstr.might+"</u></b>";
	    row.insertCell(9).innerHTML = "<b><u>"+culang.farmInactive+"</u></b>";
	    row.insertCell(10).innerHTML = "<b><u>"+culang.farmAttacks+"</u></b>";
    },

	isMyself: function(userID){
	    if(!Seed.players["u"+userID]) return false;
	    if(Seed.players["u"+userID].n == Seed.player.name) return true;
	    else return false;
	    return false;
	},

  checkFarmData: function(){
   	var t = Tabs.farm;
	  if (FarmOptions.Running == false) return;   
	  var ToSearch = [];	
    var now = unixTime();
	  for (i=1;i<=Seed.cities.length;i++){
	    t.helpArray[i] = [];
	    var myarray = (GM_getValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId()));
    	if (!FarmOptions.CityEnable[i]) continue;
    	if (myarray == undefined) ToSearch.push(i);
				else {
	       	myarray = JSON2.parse(myarray);
	       	t.helpArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
	       	GM_setValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.helpArray[i]));
	    	}	
    	}
    	if (ToSearch.length > 0){
				t.mapblocks = [];
    		document.getElementById('FarmSearchPR').innerHTML=''+culang.searchStartSearching+':  <span id="SearchFarm"></span> <span id="MapSearchActiveFarm"></span>';
    		
				for (i=0;i<ToSearch.length;i++) {
    			X = parseInt(Seed.cities[ToSearch[i]-1][2]);
          Y = parseInt(Seed.cities[ToSearch[i]-1][3]);
					t.MakeBlocks(X, Y, (ToSearch[i]), (i + 1), ToSearch.length);
    		}
				t.doSearch();
    	} else t.FilterFarms();
 	},

 	MakeBlocks:function(getX,getY,city,i,length){
    var t = Tabs.farm;
    var blocks = [];
		var xx = 0;
		var yy = 0;
		var blockcounter = 0;
		for (x = (getX - 35); x <= (getX + 35); x += 5) {
			for (y = (getY - 35); y <= (getY + 35); y += 5) {
				xx = x;
				yy = y;
				if (x > 750) xx -= 750;
				if (y > 750) yy -= 750;
				if (x < 0) xx += 750;
				if (y < 0) yy += 750;
				blocks.push("bl_" + xx + "_bt_" + yy);
				blockcounter++;
			}
		}
		//Aufteilen in kleinere Mengen a 20 blocks
		var max = ~~(blockcounter/searchblocks) + 1;
		var blo = [];
		for (var split = 0; split < max; split++) {
			blo = [];
			for (var z = 0; z < searchblocks; z++) {
				if (blocks.length > 0) {
					blo.push(blocks[0]);
					blocks.shift();
				}
			}
			var o = {
				'x'	: getX,
				'y'	: getY,
				'c'	: city,
				'i'	: i,
				'l'	: length,
				'm' : max,
				's' : split+1,
				'b'	: blo,
			};
			t.mapblocks.push(o);		
		}
  },

  doSearch:function (pass,xx,yy,city,i,length){
    var t = Tabs.farm;
		if (MapSearchActive == "") {
			MapSearchActive = culang.tabLabelAutoFarm;
		} 	
		if (MapSearchActive != culang.tabLabelAutoFarm)  {
			var rep = {
				'tab' : MapSearchActive,
			};
			ById('MapSearchActiveFarm').innerHTML = culang.MapSearchActive.mreplace(rep);
			setTimeout(t.doSearch, 5000);
			return;
		} else if (t.mapblocks.length > 0) {
			ById('MapSearchActiveFarm').innerHTML = '';
		}
		if (t.mapblocks.length > 0) {
			//Suchdaten auslesen
			var mdata = t.mapblocks[0];
			var blocks = mdata.b;
			var xx = mdata.x;
			var yy = mdata.y;
			var city = mdata.c;
			var i = mdata.i;
			var length = mdata.l;
			var max = mdata.m;
			var s = mdata.s;
		} else {
			//Keine weitern Suchdaten
			MapSearchActive = "";
			return;
		}
		
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = blocks;
		
    new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok) {
					if (rslt.error_code == 9) {
						//Map Error
						ById('MapSearchActiveFarm').innerHTML = 'Map Error (60 Sec)';
						setTimeout(t.doSearch, 61000);
						return;
					}	
					ById('SearchFarm').innerHTML = '('+i+'/'+length+') - ('+s+'/'+max+')';
					//Startet die Teilsuche?
					if (s == 1) t.mapDat = [];
					
					var map = rslt.data;
          for (k in map) {
            var dist = distance(xx, yy, map[k].xCoord, map[k].yCoord);
				    var CityCheck = true;
				    var who = "u" + map[k].tileUserId;
				    var AllianceName = "";
				    if (map[k].cityName == null && map[k].misted ==false) CityCheck = false;
        		if (t.isMyself(map[k].tileUserId)) CityCheck = false;
            if (map[k].tileType== 51 && CityCheck) {
             	var Diplomacy = "neutral";
            	for (DipStatus in t.DipArray) {
								var AllianceId = 0;
								if (rslt.userInfo[who] != undefined) AllianceId = "a" + rslt.userInfo[who].a;                
								for (alliance in Seed.allianceDiplomacies[t.DipArray[DipStatus]]) 
									if (Seed.allianceDiplomacies[t.DipArray[DipStatus]][AllianceId] != undefined) 
										Diplomacy = t.DipArray[DipStatus];
            	}
            	if (rslt.allianceNames[AllianceId] != undefined) AllianceName = rslt.allianceNames[AllianceId];
            	if (Diplomacy == "neutral" && AllianceName =="") Diplomacy = "unallied";
            	t.mapDat.push ({time:0,empty:0,lost:false,enabled:'true',attacked:0,DaysInactive:"?",LastCheck:0,Diplomacy:Diplomacy,UserId:map[k].tileUserId,AllianceName:AllianceName,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel,PlayerName:rslt.userInfo[who].n,cityName:map[k].cityName,might:rslt.userInfo[who].m,cityNumber:map[k].cityNum});
            }
          }
					
					//Teilsuche
					if (s == max) {
						//Teilsuche in der Stadt beendet
						FarmOptions.FarmNumber[city] = 0;
						FarmOptions.Attacks = 0;
						FarmOptions.Checks = 0;
						GM_setValue('Farms_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.mapDat));  
						var myarray = (GM_getValue('Farms_' + Seed.player['name'] + '_city_' + city + '_' + getServerId()));
						myarray = JSON2.parse(myarray);
						t.helpArray[city] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});                               
					}
					 
					if (i == length && s == max) {
						//Suche Beendet
						document.getElementById('FarmSearchPR').innerHTML = "";
						t.FilterFarms();
					}
         
        } else {
					actionLog(culang.tabLabelAutoFarm,inspect(rslt,5));
				}
				t.mapblocks.splice(0,1);
				setTimeout(t.doSearch, 500);
      },
			onFailure: function () {
				t.mapblocks.splice(0,1);
				setTimeout(t.doSearch, 500);
			},
    });
  },
  
	FilterFarms: function() {
	    var t = Tabs.farm;
	    t.FarmArray = new Array();
	    t.FarmArray["1"] = new Array();
	    t.FarmArray["2"] = new Array();
	    t.FarmArray["3"] = new Array();
	    t.FarmArray["4"] = new Array();
	    t.FarmArray["5"] = new Array();
	    t.FarmArray["6"] = new Array();
	    t.FarmArray["7"] = new Array();
	    t.FarmArray["8"] = new Array();    
	    for (var u=1;u<=Seed.cities.length;u++){        
	        for (var i in t.helpArray[u]){	
	            var checkLvl = false;
	            var checkMight = false;
	            var checkDip = false;
	            var checkAlliance = false;
	            var AllianceName = "";
	            for (j=1;j<=12;j++) if (FarmOptions.CityLevel[j] && t.helpArray[u][i].level == j) checkLvl=true;
	            if (Seed.allianceDiplomacies.allianceName != undefined) AllianceName = Seed.allianceDiplomacies.allianceName;
	            if (t.helpArray[u][i].AllianceName != AllianceName) checkAlliance = true;
	            if (t.helpArray[u][i].might >= FarmOptions.MinMight && t.helpArray[u][i].might <= FarmOptions.MaxMight) checkMight = true;
	            for (j in FarmOptions.Diplomacy) if (FarmOptions.Diplomacy[j] && t.helpArray[u][i].Diplomacy == j) checkDip=true;
	            if (checkLvl && checkMight && checkDip && checkAlliance) t.FarmArray[u].push (t.helpArray[u][i]);
	        }
	        var elem = 'pdtotalFarm'+(u-1);
	        if (t.FarmArray[u] == undefined) document.getElementById(elem).innerHTML = ''+culang.farmNoData+'';
	        else document.getElementById(elem).innerHTML =  ''+culang.farmFarms+' ' + t.FarmArray[u].length +'/'+ t.helpArray[u].length;
	    }
	},

	SortDist: function(a,b) {
	    a = parseFloat(a['dist']);
	    b = parseFloat(b['dist']);
	    return (a < b )? -1 : ((a > b ? 1 : 0));
	},
  /*
  	toggleBarbState: function(obj){
	    var t = Tabs.farm;
	    if (FarmOptions.Running == true) {
	        FarmOptions.Running = false;
	        if (document.getElementById('FarmAttSearch')) {document.getElementById('FarmAttSearch').value = ""+culang.farmButton+" = "+culang.buttonOF+"";}
			// document.getElementById('FarmAttSearch').setAttribute("class", "buttonDash_OFF");
	        if (document.getElementById('AutoFarmToggle')) {document.getElementById('AutoFarmToggle').value = ""+culang.farmButton+" = "+culang.buttonOFF+"";}
			// document.getElementById('AutoFarmToggle').setAttribute("clasfvs", "buttonDash_OFF");
	        // ClearMarchQueue("Farm");
	        saveFarmOptions();
	    } else {
	        FarmOptions.Running = true;
	        if (document.getElementById('FarmAttSearch')) {document.getElementById('FarmAttSearch').value = ""+culang.farmButton+" = "+culang.buttonON+"";}
			// document.getElementById('FarmAttSearch').setAttribute("class", "buttonDash_ON");
	        if (document.getElementById('AutoFarmToggle')) {document.getElementById('AutoFarmToggle').value = ""+culang.farmButton+" = "+culang.buttonON+"";}
			// document.getElementById('AutoFarmToggle').setAttribute("class", "buttonDash_ON");
	        saveFarmOptions();
	        t.checkFarmData();
	    }
  	},*/
	
  	toggleBarbState: function(obj){
		var t = Tabs.farm;
		if (FarmOptions.Running == true) {
			FarmOptions.Running = false;
			obj.value = culang.farmButton+' = '+culang.buttonOFF;
			ClearMarchQueue("Farm");
			saveFarmOptions();
			// t.nextattack = null;
			// t.updateSeedTimer = null;
		} else {
			var en = false;
			for (var i=1;i<=Seed.cities.length;i++) {
				if (FarmOptions.CityEnable[i]) en = true;
			}
			if (en) {
				FarmOptions.Running = true;
				obj.value = culang.farmButton+' = '+culang.buttonON;
			saveFarmOptions();
			t.checkFarmData();
			}
		}
	},
  	barbing : function(cityID,whatcity){
        var t = Tabs.farm;
       	var city = whatcity +1;
       	if (!FarmOptions.CityEnable[city]) return;
       	if (t.FarmArray[city].length == 0) return;
       	var u1 = FarmOptions.Troops[1];
       	var u2 = FarmOptions.Troops[2];
       	var u3 = FarmOptions.Troops[3];
       	var u4 = FarmOptions.Troops[4];
       	var u5 = FarmOptions.Troops[5];
       	var u6 = FarmOptions.Troops[6];
       	var u7 = FarmOptions.Troops[7];
       	var u8 = FarmOptions.Troops[8];
       	var u9 = FarmOptions.Troops[9];
       	var u10 = FarmOptions.Troops[10];
       	var u11 = FarmOptions.Troops[11];
       	var u12 = FarmOptions.Troops[12];
       	var now = new Date().getTime()/1000.0;
       	now = now.toFixed(0);    
        if (FarmOptions.FarmNumber[city]>=t.FarmArray[city].length) FarmOptions.FarmNumber[city]=0;
        var interval = 0;
        switch(FarmOptions.Interval){
            case "1":interval = 1;break;
            case "2":interval = 2;break;
            case "3":interval = 3;break;
            case "4":interval = 6;break;
            case "5":interval = 12;break;
            case "6":interval = 24;break;
        }        
        var check=0;
        while (check == 0){
	        check=1;
	       	if (!t.FarmArray[city][FarmOptions.FarmNumber[city]]['enabled']) check=0;
	       	if (now < (parseInt(t.FarmArray[city][FarmOptions.FarmNumber[city]]['time']) + (3600 * interval))) check=0;
	       	if (check ==0) FarmOptions.FarmNumber[city]++;
	       	if (FarmOptions.FarmNumber[city]>=t.FarmArray[city].length) {
               	FarmOptions.FarmNumber[city]=0;
                break;
	        }
       	}
        if (check == 0) return;
        var xcoord = t.FarmArray[city][FarmOptions.FarmNumber[city]]['x'];
        var ycoord = t.FarmArray[city][FarmOptions.FarmNumber[city]]['y'];
        var uid = t.FarmArray[city][FarmOptions.FarmNumber[city]]['UserId'];
        saveFarmOptions();
        t.checkInactives(cityID,city,FarmOptions.FarmNumber[city],xcoord,ycoord,uid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12);
  	},

	checkInactives : function (citynumber,city,FarmNumber,xcoord,ycoord,uid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12){
	    var t = Tabs.farm;
	    var now = new Date().getTime()/1000.0;
	    var hours = (now - t.FarmArray[city][FarmOptions.FarmNumber[city]]['LastCheck']) / 3600;
	    if (t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] == "?" || hours > 6){
            var params = uW.Object.clone(uW.g_ajaxparams);
            params.pid = uid;
            
            new AjaxRequest(uW.g_ajaxpath + "ajax/viewCourt.php" + uW.g_ajaxsuffix, {
                 method: "post",
                  parameters: params,
                  onSuccess: function (transport) {
                        var rslt = eval("(" + transport.responseText + ")");
												if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
                        var lastLogin = rslt.playerInfo.lastLogin;
                        var fullDate = lastLogin.substr(0,4) +", "+ lastLogin.substr(5,2) +", "+ lastLogin.substr(8,2) ;
                        var time = new Date (fullDate).getTime()/1000;
                        var days = Math.floor((now - time) / 86400);
                        t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] = days;
                        for (i=0;i<t.helpArray[city].length;i++){
                            if (xcoord == parseInt(t.helpArray[city][i]['x']) && ycoord == parseInt(t.helpArray[city][i]['y'])){
                                t.helpArray[city][i]['DaysInactive'] = days;
                                t.helpArray[city][i]['LastCheck'] = now;
                            }    
                        }
                        GM_setValue('Farms_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.helpArray[city]));
                        if (days > FarmOptions.Inactive) {
                            t.doBarb(citynumber,city,FarmNumber,xcoord,ycoord,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12);
                        } else {
                            FarmOptions.FarmNumber[city]++;
                            saveFarmOptions();
                        }
                   },
                  onFailure: function (rslt) {},
            });
	    } else {
	        if (t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] > FarmOptions.Inactive) t.doBarb(citynumber,city,FarmNumber,xcoord,ycoord,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12);
	         else{
                FarmOptions.FarmNumber[city]++;
                saveFarmOptions();
	        }
	    }
	},
    
  	doBarb: function(cityID,counter,number,xcoord,ycoord,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12){
        var t = Tabs.farm;
        MarchQueue[counter].push ({
    		what: 			"Farm",
			city: 			cityID,
			action: 		4,
			targetX: 		xcoord,
			targetY: 		ycoord,
			1: 				u1,
			2: 				u2,
			3: 				u3,
			4: 				u4,
			5: 				u5,
			6: 				u6,
			7: 				u7,
			8: 				u8,
			9: 				u9,
			10: 			u10,
			11: 			u11,
			12: 			u12,
			13: 			0,
			14: 			0,
			15: 			0,
        });
		var now = new Date().getTime()/1000.0;
		now = now.toFixed(0);
		t.FarmArray[counter][number]['time'] = now;
		t.FarmArray[counter][number]['attacked']++;
		FarmOptions.FarmNumber[counter]++;
		FarmOptions.Attacks++;	
		document.getElementById('FarmCheck').innerHTML = ""+culang.farmChecksAttacks+" " + FarmOptions.Attacks + " "+culang.farmChecksChecks+" " + FarmOptions.Checks;
		for (i=0;i<t.helpArray[counter].length;i++){
		    for (j=0;j<t.FarmArray[counter].length;j++){
		         if (parseInt(t.FarmArray[counter][j]['x']) == parseInt(t.helpArray[counter][i]['x']) && parseInt(t.FarmArray[counter][j]['y']) == parseInt(t.helpArray[counter][i]['y'])){
		                   t.helpArray[counter][i]['time'] = t.FarmArray[counter][j]['time'];
		                   t.helpArray[counter][i]['attacked'] = t.FarmArray[counter][j]['attacked'];
		               }    
		    }
		}
		GM_setValue('Farms_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.helpArray[counter]));  
		saveFarmOptions();
  },

  hide : function (){},
  show : function (){},

};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Crest.js">
//	
//	   KOC POWER - TABS CREST											        
//	


Tabs.Crest = {
	tabOrder: TabOptions.toCrest,
	tabLabel: culang.tabLabelCrest,
	myDiv : null,
	rallypointlevel:null,
	error_code: 0,
	knt:{},

	/** window display **/
	init : function (div){
		var t = Tabs.Crest;
		if (typeof Options.send2wave == "undefined") Options.send2wave = false;
		Options.crestMarchError = 0;
		crestTogObj = ById('Cresttoggle');

		setInterval(t.sendCrestReport, 1*60*1000);
		setTimeout(function(){ t.Rounds(1,0,0);}, 5*1000);
		setTimeout(function() {

			if (Options.crestRunning == false) {
				if (crestTogObj) crestTogObj.value = culang.tabLabelCrest+" = "+culang.buttonOFF;
			} else {
				if (crestTogObj) crestTogObj.value = culang.tabLabelCrest+" = "+culang.buttonON;
			}

		},500);

		t.myDiv = div;
		var selbut=0;
		var m = '<DIV id=pbCrestTab class=pdxStat>'+culang.crestHead+'</div><TABLE id=pbcrestfunctions width=100% height=0% class=pdxTab>';

		m += '<TR align="left">';
		m += '<td>'+culang.mainIntervall+': <INPUT type=text size=3 value='+Options.Crestinterval+' id=pbcrest_interval /> '+culang.mainSeconds+'</td>';
		m += '<td>'+culang.crestKeepRPSlots+' <INPUT id=bocrestslot value='+Options.CrestSlot+' type=text size=2 \> '+culang.crestKeepRPSlots2+'</td>';
		m += '<td><INPUT id=showCrestTargets type=submit value="'+culang.crestRoute+'"></td>';

		if (Options.crestRunning == false) {
			m += '<TD><INPUT id=Cresttoggle type=submit value="'+culang.tabLabelCrest+' = '+culang.buttonOFF+'"></td>';
		} else {
			m += '<TD><INPUT id=Cresttoggle type=submit value="'+culang.tabLabelCrest+' = '+culang.buttonON+'"></td>';
		}
		m += '<TD><INPUT id=CrestHelp type=submit value="'+culang.buttonHelp+'"></td></tr>';

		m += '<tr><TD colspan=3><INPUT id=pbsendreport type=checkbox '+ (Options.crestreport?' CHECKED':'') +'\> '+culang.crestEnableReports+' -  &nbsp; '+culang.mainIntervall+' <INPUT id=pbsendcrestreportint value='+ Options.CrestMsgInterval +' type=text size=3 \> '+culang.mainHours+' <input type=button value="'+culang.buttonSendCrest+'" id=bosendreportnow></td></tr>';
		m += '<tr><TD colspan=3><INPUT id=pb2wave type=checkbox '+ (Options.send2wave?' CHECKED':'') +'\> '+culang.send2wave+'</td></tr>';
		m += '</table>';

		m += '<DIV id=pbOpt class=pdxStat>'+culang.crestHeadSettings+'</div>';
		m += '<DIV style="margin-bottom:10px;"><b>'+culang.mainCastle+'</b>: <span id=crestcity></span></div>';
		m += '<TABLE class=pdxTab><TR><TD><b>'+culang.mainCoord+'</b>: &nbsp;&nbsp;X:<INPUT id=pbcrestx type=text size=3 maxlength=3 value=""></td>';
		m += '<TD>Y:<INPUT id=pbcresty type=text size=3 maxlength=3 value=""></td></tr></table>';
		m += '<TABLE class=pdxTab><TR><TD>'+culang.crestWave+' <b>1</b>: </td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyTroop+'"></td><TD><INPUT id=R1ST type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleMilitiaman+'"></td><TD><INPUT id=R1MM type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleScout+'"></td><TD><INPUT id=R1Scout type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddlePikeman+'"></td><TD><INPUT id=R1Pike type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSwordsman+'"></td><TD><INPUT id=R1Sword type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleArcher+'"></td><TD><INPUT id=R1Arch type=text size=7 maxlength=6 value=0></td></tr>';
		m += '<tr><td></td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleCavalry+'"></td><TD><INPUT id=R1LC type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleHeavyCavalry+'"></td><TD><INPUT id=R1HC type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyWagon+'"></td><TD><INPUT id=R1SW type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBallista+'"></td><TD><INPUT id=R1Ball type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBatteringRam+'"></td><TD><INPUT id=R1Ram type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleCatapult+'"></td><TD><INPUT id=R1Cat type=text size=7 maxlength=6 value=0></td></tr>';

		m += '<tr><td></td><TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50.jpg"></td><TD><INPUT id=R1BT type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50.jpg"></td><TD><INPUT id=R1EX type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50.jpg"></td><TD><INPUT id=R1SWa type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
		m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
		m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td></tr>';

		m += '<tr><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>';
		
		m += '<TR><TD>'+culang.crestWave+' <b>2</b>: </td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyTroop+'"></td><TD><INPUT id=R2ST type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleMilitiaman+'"></td><TD><INPUT id=R2MM type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleScout+'"></td><TD><INPUT id=R2Scout type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddlePikeman+'"></td><TD><INPUT id=R2Pike type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSwordsman+'"></td><TD><INPUT id=R2Sword type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleArcher+'"></td><TD><INPUT id=R2Arch type=text size=7 maxlength=6 value=0></td></tr>';
		m += '<tr><td></td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleCavalry+'"></td><TD><INPUT id=R2LC type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleHeavyCavalry+'"></td><TD><INPUT id=R2HC type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyWagon+'"></td><TD><INPUT id=R2SW type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBallista+'"></td><TD><INPUT id=R2Ball type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBatteringRam+'"></td><TD><INPUT id=R2Ram type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleCatapult+'"></td><TD><INPUT id=R2Cat type=text size=7 maxlength=6 value=0></td></tr>';

		m += '<tr><td></td><TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50.jpg"></td><TD><INPUT id=R2BT type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50.jpg"></td><TD><INPUT id=R2EX type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50.jpg"></td><TD><INPUT id=R2SWa type=text size=7 maxlength=6 value=0></td>';
		m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
		m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
		m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td></tr>';
		
		m += '</table>';
		m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteCrest type=submit value="'+culang.crestAdd+'"></div>';

		t.myDiv.innerHTML = m;
		ById('bocrestslot').addEventListener('change', function(){
			if (parseIntNan(document.getElementById('bocrestslot').value)>9) document.getElementById('bocrestslot').value=1;
			Options.CrestSlot = document.getElementById('bocrestslot').value;
			saveOptions();
		}, false);

		ById('pb2wave').addEventListener('change', function(){
			Options.send2wave = document.getElementById('pb2wave').checked;
			saveOptions();
		}, false);
		ById('pbsendreport').addEventListener('change', function(){
			Options.crestreport = document.getElementById('pbsendreport').checked;
			saveOptions();
		}, false);
		ById('pbsendcrestreportint').addEventListener('change', function(){
			Options.CrestMsgInterval = parseIntNan(document.getElementById('pbsendcrestreportint').value);
			saveOptions();
		}, false);
		ById("pbcrest_interval").addEventListener('change', function(e){
			if (parseIntNan(e.target.value)<5) e.target.value=5;
			Options.Crestinterval = parseIntNan(e.target.value);
			saveOptions();
		},false);
		for (var i=0;i<Seed.cities.length;i++){
			if (CrestOptions.CrestCity == Seed.cities[i][0]){
				selbut=i;
				break;
			}
		}

		t.tcp = new CdispCityPicker ('crestcityselect', document.getElementById('crestcity'), true, t.clickCitySelect, selbut);

		if (CrestOptions.CrestCity == 0) {
			CrestOptions.CrestCity = t.tcp.city.id
		}
		ById('bosendreportnow').addEventListener('click', function() {
			t.sendCrestReportNow();

		}, false);

		document.getElementById('pbcrestx').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('pbcrestx').value)) document.getElementById('pbcrestx').value='' ;
		}, false);

		document.getElementById('pbcresty').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('pbcresty').value)) document.getElementById('pbcresty').value='' ;
		}, false);

		document.getElementById('R1ST').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1ST').value)) document.getElementById('R1ST').value=0 ;
		}, false);

		document.getElementById('R1MM').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1MM').value)) document.getElementById('R1MM').value=0 ;
		}, false);

		document.getElementById('R1Pike').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Pike').value)) document.getElementById('R1Pike').value=0 ;
		}, false);

		document.getElementById('R1Scout').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Scout').value)) document.getElementById('R1Scout').value=0 ;
		}, false);

		document.getElementById('R1Sword').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Sword').value)) document.getElementById('R1Sword').value=0 ;
		}, false);

		document.getElementById('R1Arch').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Arch').value)) document.getElementById('R1Arch').value=0 ;
		}, false);

		document.getElementById('R1LC').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1LC').value)) document.getElementById('R1LC').value=0 ;
		}, false);

		document.getElementById('R1HC').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1HC').value)) document.getElementById('R1HC').value=0 ;
		}, false);

		document.getElementById('R1SW').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1SW').value)) document.getElementById('R1SW').value=0 ;
		}, false);

		document.getElementById('R1Ball').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Ball').value)) document.getElementById('R1Ball').value=0 ;
		}, false);

		document.getElementById('R1Ram').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Ram').value)) document.getElementById('R1Ram').value=0 ;
		}, false);

		document.getElementById('R1Cat').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1Cat').value)) document.getElementById('R1Cat').value=0 ;
		}, false);

		document.getElementById('R1BT').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1BT').value)) document.getElementById('R1BT').value=0 ;
		}, false);
		
		document.getElementById('R1EX').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1EX').value)) document.getElementById('R1EX').value=0 ;
		}, false);		
		
		document.getElementById('R1SWa').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R1SWa').value)) document.getElementById('R1SWa').value=0 ;
		}, false);		
		
		document.getElementById('R2ST').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2ST').value)) document.getElementById('R2ST').value=0 ;
		}, false);

		document.getElementById('R2MM').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2MM').value)) document.getElementById('R2MM').value=0 ;
		}, false);

		document.getElementById('R2Pike').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Pike').value)) document.getElementById('R2Pike').value=0 ;
		}, false);

		document.getElementById('R2Scout').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Scout').value)) document.getElementById('R2Scout').value=0 ;
		}, false);

		document.getElementById('R2Sword').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Sword').value)) document.getElementById('R2Sword').value=0 ;
		}, false);

		document.getElementById('R2Arch').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Arch').value)) document.getElementById('R2Arch').value=0 ;
		}, false);

		document.getElementById('R2LC').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2LC').value)) document.getElementById('R2LC').value=0 ;
		}, false);

		document.getElementById('R2HC').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2HC').value)) document.getElementById('R2HC').value=0 ;
		}, false);

		document.getElementById('R2SW').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2SW').value)) document.getElementById('R2SW').value=0 ;
		}, false);

		document.getElementById('R2Ball').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Ball').value)) document.getElementById('R2Ball').value=0 ;
		}, false);

		document.getElementById('R2Ram').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Ram').value)) document.getElementById('R2Ram').value=0 ;
		}, false);

		document.getElementById('R2Cat').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2Cat').value)) document.getElementById('R2Cat').value=0 ;
		}, false);

		document.getElementById('R2BT').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2BT').value)) document.getElementById('R2BT').value=0 ;
		}, false);
	
		document.getElementById('R2EX').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2EX').value)) document.getElementById('R2EX').value=0 ;
		}, false);
		
		document.getElementById('R2SWa').addEventListener('keyup', function(){
			if (isNaN(document.getElementById('R2SWa').value)) document.getElementById('R2SWa').value=0 ;
		}, false);
		
		document.getElementById('crestcity').addEventListener('click', function(){CrestOptions.CrestCity = t.tcp.city.id;} , false);
		document.getElementById('Cresttoggle').addEventListener('click', function(){t.toggleCrestState(this)} , false);
		document.getElementById('pbcrestx').addEventListener('change', function(){CrestOptions.X = document.getElementById('pbcrestx').value;;} , false);
		document.getElementById('pbcresty').addEventListener('change', function(){CrestOptions.Y = document.getElementById('pbcresty').value;} , false);
		document.getElementById('R1ST').addEventListener('change', function(){CrestOptions.R1ST = document.getElementById('R1ST').value;} , false);
		document.getElementById('R1MM').addEventListener('change', function(){CrestOptions.R1MM = document.getElementById('R1MM').value;} , false);
		document.getElementById('R1Scout').addEventListener('change', function(){CrestOptions.R1Scout = document.getElementById('R1Scout').value;} , false);
		document.getElementById('R1Pike').addEventListener('change', function(){CrestOptions.R1Pike = document.getElementById('R1Pike').value;} , false);
		document.getElementById('R1Sword').addEventListener('change', function(){CrestOptions.R1Sword = document.getElementById('R1Sword').value;} , false);
		document.getElementById('R1Arch').addEventListener('change', function(){CrestOptions.R1Arch = document.getElementById('R1Arch').value;} , false);
		document.getElementById('R1LC').addEventListener('change', function(){CrestOptions.R1LC = document.getElementById('R1LC').value;} , false);
		document.getElementById('R1HC').addEventListener('change', function(){CrestOptions.R1HC = document.getElementById('R1HC').value;} , false);
		document.getElementById('R1SW').addEventListener('change', function(){CrestOptions.R1SW = document.getElementById('R1SW').value;} , false);
		document.getElementById('R1Ball').addEventListener('change', function(){CrestOptions.R1Ball = document.getElementById('R1Ball').value;} , false);
		document.getElementById('R1Ram').addEventListener('change', function(){CrestOptions.R1Ram = document.getElementById('R1Ram').value;} , false);
		document.getElementById('R1Cat').addEventListener('change', function(){CrestOptions.R1Cat = document.getElementById('R1Cat').value;} , false);
		document.getElementById('R1BT').addEventListener('change', function(){CrestOptions.R1BT = document.getElementById('R1BT').value;} , false);
		document.getElementById('R1EX').addEventListener('change', function(){CrestOptions.R1EX = document.getElementById('R1EX').value;} , false);
		document.getElementById('R1SWa').addEventListener('change', function(){CrestOptions.R1SWa = document.getElementById('R1SWa').value;} , false);

		document.getElementById('R2ST').addEventListener('change', function(){CrestOptions.R2ST = document.getElementById('R2ST').value;} , false);
		document.getElementById('R2MM').addEventListener('change', function(){CrestOptions.R2MM = document.getElementById('R2MM').value;} , false);
		document.getElementById('R2Scout').addEventListener('change', function(){CrestOptions.R2Scout = document.getElementById('R2Scout').value;} , false);
		document.getElementById('R2Pike').addEventListener('change', function(){CrestOptions.R2Pike = document.getElementById('R2Pike').value;} , false);
		document.getElementById('R2Sword').addEventListener('change', function(){CrestOptions.R2Sword = document.getElementById('R2Sword').value;} , false);
		document.getElementById('R2Arch').addEventListener('change', function(){CrestOptions.R2Arch = document.getElementById('R2Arch').value;} , false);
		document.getElementById('R2LC').addEventListener('change', function(){CrestOptions.R2LC = document.getElementById('R2LC').value;} , false);
		document.getElementById('R2HC').addEventListener('change', function(){CrestOptions.R2HC = document.getElementById('R2HC').value;} , false);
		document.getElementById('R2SW').addEventListener('change', function(){CrestOptions.R2SW = document.getElementById('R2SW').value;} , false);
		document.getElementById('R2Ball').addEventListener('change', function(){CrestOptions.R2Ball = document.getElementById('R2Ball').value;} , false);
		document.getElementById('R2Ram').addEventListener('change', function(){CrestOptions.R2Ram = document.getElementById('R2Ram').value;} , false);
		document.getElementById('R2Cat').addEventListener('change', function(){CrestOptions.R2Cat = document.getElementById('R2Cat').value;} , false);
		document.getElementById('R2BT').addEventListener('change', function(){CrestOptions.R2BT = document.getElementById('R2BT').value;} , false);
		document.getElementById('R2EX').addEventListener('change', function(){CrestOptions.R2EX = document.getElementById('R2EX').value;} , false);
		document.getElementById('R2SWa').addEventListener('change', function(){CrestOptions.R2SWa = document.getElementById('R2SWa').value;} , false);
		
		document.getElementById('CrestHelp').addEventListener('click', function(){t.helpPop();} , false);
		document.getElementById('pbSaveRouteCrest').addEventListener('click', function(){CrestOptions.active=""+culang.mainDeActivate+"";t.addCrestRoute();}, false);
		document.getElementById('showCrestTargets').addEventListener('click', function(){t.showCrestRoute();}, false);
	},


	helpPop : function (){
		var helpText = culang.crestHelp;

		var pop = new CPopup ('ArmoiriesHelp', 0, 0, 600, 420, true);
		pop.centerMe (mainPop.getMainDiv());
		pop.getMainDiv().innerHTML = helpText;
		pop.getTopDiv().innerHTML = '<div class="popupBanner"> '+culang.crestHelpPopupHead+' </div>';
		pop.show (true);
	},
	addCrestRoute : function () {
		if(CrestOptions.X == "" || CrestOptions.Y == "") {
			alert("Pas de coordonnees !");
			return;
		}
		var t = Tabs.Crest;
		var CrestLength = CrestData.length;
		CrestData[CrestLength] = new CrestFunc(CrestOptions);
		saveCrestData();
	},
	showCrestRoute : function () {
		var t = Tabs.Crest;
		var popCrestTargets = null;
		t.popCrestTargets = new CPopup('pbShowCrestTargets', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowCrestTargets" id="pbCrestTargets">';
		t.popCrestTargets.getMainDiv().innerHTML = '</table></div>' + m;
		t.popCrestTargets.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.crestRoute+'</div>';
		t.paintCrestTargets();
		t._addTabHeader();
		t.popCrestTargets.show(true);

	},

	/** add header **/
	_addTabHeader : function () {
		var row = document.getElementById('pbCrestTargets').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = "<u><b>"+culang.crestRoute1+"</b></u>";
		row.insertCell(1).innerHTML = "<u><b>"+culang.crestWave+" #</b></u>";
		row.insertCell(2).innerHTML = "<img width=25 src='"+IMGmiddleSupplyTroop+"'>";
		row.insertCell(3).innerHTML = "<img width=25 src='"+IMGmiddleMilitiaman+"'>";
		row.insertCell(4).innerHTML = "<img width=25 src='"+IMGmiddleScout+"'>";
		row.insertCell(5).innerHTML = "<img width=25 src='"+IMGmiddlePikeman+"'>";
		row.insertCell(6).innerHTML = "<img width=25 src='"+IMGmiddleSwordsman+"'>";
		row.insertCell(7).innerHTML = "<img width=25 src='"+IMGmiddleArcher+"'>";
		row.insertCell(8).innerHTML = "<img width=25 src='"+IMGmiddleCavalry+"'>";
		row.insertCell(9).innerHTML = "<img width=25 src='"+IMGmiddleHeavyCavalry+"'>";
		row.insertCell(10).innerHTML = "<img width=25 src='"+IMGmiddleSupplyWagon+"'>";
		row.insertCell(11).innerHTML = "<img width=25 src='"+IMGmiddleBallista+"'>";
		row.insertCell(12).innerHTML = "<img width=25 src='"+IMGmiddleBatteringRam+"'>";
		row.insertCell(13).innerHTML = "<img width=25 src='"+IMGmiddleCatapult+"'>";
		row.insertCell(14).innerHTML = '<img width=25 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50.jpg">';
		row.insertCell(15).innerHTML = '<img width=25 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50.jpg">';
		row.insertCell(16).innerHTML = '<img width=25 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50.jpg">';
		row.insertCell(17).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
		row.insertCell(18).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	},

	/** paintCrestTargets **/
	paintCrestTargets : function () {
		t = Tabs.Crest;
		for(var i = 0; i < CrestData.length; i++) {
			t._addTabCrest(i, '<b>'+culang.crestTarget+'<b>: <a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">(' + CrestData[i].X + ',' + CrestData[i].Y+')</a>', "<b>2</b>", CrestData[i].R2ST, CrestData[i].R2MM, CrestData[i].R2Scout, CrestData[i].R2Pike, CrestData[i].R2Sword, CrestData[i].R2Arch, CrestData[i].R2LC, CrestData[i].R2HC, CrestData[i].R2SW, CrestData[i].R2Ball, CrestData[i].R2Ram, CrestData[i].R2Cat, CrestData[i].R2BT, CrestData[i].R2EX, CrestData[i].R2SWa," "," ");
			t._addTabCrest(i, CrestData[i].CrestCity, "<b>1</b>", CrestData[i].R1ST, CrestData[i].R1MM, CrestData[i].R1Scout, CrestData[i].R1Pike, CrestData[i].R1Sword, CrestData[i].R1Arch, CrestData[i].R1LC, CrestData[i].R1HC, CrestData[i].R1SW, CrestData[i].R1Ball, CrestData[i].R1Ram, CrestData[i].R1Cat, CrestData[i].R1BT, CrestData[i].R1EX, CrestData[i].R1SWa, culang.mainDelete, CrestData[i].active);
			t._addTabCrest(i, "","","","","","","","","","","","","","","","","","","");
		}
	},

	/** Add Tab Crest **/
	_addTabCrest : function (QueID, col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16, col17,col18) {
		var t = Tabs.Crest;
		var row = document.getElementById('pbCrestTargets').insertRow(0);

		for (var i = 0; i <= 18; i++) {
			if (i == 17 && col17 == culang.mainDelete) {
				row.insertCell(i).innerHTML = "<a id=pbCrestDel_" + QueID + " value=" + i + "><img src='"+IMGdeleteButton+"' border=0 title='"+culang.mainDelete+"' alt='"+culang.mainDelete+"'></a>";
				document.getElementById('pbCrestDel_' + QueID).addEventListener('click', function(){t.cancelCrestTarget(QueID);}, false);
			} else if (col17 == culang.mainDelete && i == 0) {
				row.insertCell(i).innerHTML = Cities.byID[col0].name;
			} else if  (i == 18 && col17 == culang.mainDelete) {

				if (CrestData[QueID].active==""+culang.mainDeActivate+"") {
					row.insertCell(i).innerHTML = "<a id=KsCrestAct_" + QueID + " value=" + i + ">"+culang.mainDeActivate+"</a>";
					document.getElementById('KsCrestAct_' + QueID).addEventListener('click', function(){ CrestData[QueID].active=""+culang.mainActivate+"";saveCrestData();t.showCrestRoute();  }, false);
				} else if (CrestData[QueID].active==""+culang.mainActivate+"") {
					row.insertCell(i).innerHTML = "<a id=KsCrestAct_" + QueID + " value=" + i + ">"+culang.mainActivate+"</a>";
					document.getElementById('KsCrestAct_' + QueID).addEventListener('click', function(){ CrestData[QueID].active=""+culang.mainDeActivate+"";saveCrestData();t.showCrestRoute();  }, false);
				}
			}else{
				row.insertCell(i).innerHTML = eval("col" + i) + "&nbsp; &nbsp;";
			}
		}
	},

	/** Cancel Crest Target **/
	cancelCrestTarget : function (QueID) {
		var t = Tabs.Crest;
		var queueId = parseInt(QueID);
		CrestData.splice(queueId, 1);
		saveCrestData();
		t.showCrestRoute();
	},

	getRallypointLevel: function(cityId){
		var t = Tabs.Crest;
		for (var o in Seed.buildings[cityId]){
			var buildingType = parseInt(Seed.buildings[cityId][o][0]);
			var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
			if (buildingType == 12)
				t.rallypointlevel=parseInt(buildingLevel);
		}
	},

	getAtkKnight : function(cityID){
		var t = Tabs.Crest;
		t.knt = new Array();
		for (k in Seed.knights[cityID]){
			if (Seed.knights[cityID][k]["knightStatus"] == 1 && 
					Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && 
					Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && 
					Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && 
					Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"]){
				t.knt.push ({
					Name:   Seed.knights[cityID][k]["knightName"],
					Combat:	parseInt(Seed.knights[cityID][k]["combat"]),
					ID:			Seed.knights[cityID][k]["knightId"],
				});
			}
		}
		t.knt = t.knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
	},

	sendMarch: function(p,callback,r,retry, CrestDataNum){
		var t = Tabs.Crest;

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: p,
			loading: true,
			onSuccess: function (rslt) {
					if (rslt.ok) {
						var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
						var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
						var ut = uW.unixtime();
						var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
						for(i = 0; i <= unitsarr.length; i++){
							if(p["u"+i]){
								unitsarr[i] = p["u"+i];
							}
						}
						var resources=new Array();
						resources[0] = p.gold;
						for(i=1; i<=4; i++){
							resources[i] = p["r"+i];
						}
						var currentcityid = p.cid;
						uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, p.xcoord, p.ycoord, unitsarr, p.type, p.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
								 
						var now = new Date().getTime()/1000.0;
						now = now.toFixed(0);
						var rep = {
							'city' : Cities.byID[p.cid].name,
							'koords' : p.xcoord + "," +p.ycoord,
							'wave' : r,
						};
						actionLog(""+culang.tabLabelCrest+"",culang.crestmsgOK.mreplace(rep));
						if(r==1){
							Options.Crest1Count++;
							r = 2;
							CrestData[CrestDataNum].lastRoundTwo = now;
						} else {
							Options.Crest2Count++;						
							if (Options.send2wave) {
								CrestDataNum++;
								r = 1;
							}
						}
						saveCrestData();
						t.timer = setTimeout (function(){callback(r,0,CrestDataNum);}, (Math.random()*5*1000)+(Options.Crestinterval*1000));
						return;

					} else {
						if (rslt.user_action) {
							actionLog(""+culang.tabLabelCrest+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
							new CdialogCancelContinue('<SPAN class=boldRed>'+culang.crestCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);
							t.timer = setTimeout (function(){callback(r,retry,CrestDataNum);},10*60*1000);
							return;
						}
						var rep = {
							'city' : Cities.byID[p.cid].name,
							'koords' : p.xcoord + "," +p.ycoord,
							'wave' : r,
							'error' : '<span class=boldRed>'+rsltErrorCode(rslt)+'</span>',
						};
						actionLog(culang.tabLabelCrest,culang.crestmsgError.mreplace(rep));
						t.timer = setTimeout (function(){callback(r,retry,CrestDataNum);}, Options.Crestinterval*1000);
						return;
					}
				
			},
			onFailure: function () {
						var rep = {
							'city' : Cities.byID[p.cid].name,
							'koords' : p.xcoord + "," +p.ycoord,
							'wave' : r,
						};
						actionLog(""+culang.tabLabelCrest+"",culang.crestmsgFatalError.mreplace(rep));
				setTimeout (function(){callback(r,retry,CrestDataNum);}, Options.Crestinterval*1000);
				return;
			}
		});
	},

	abandonWilderness: function(tid,x,y,cid,callback,retry, CrestDataNum){
		var t = Tabs.Crest;
		if (!Options.crestRunning) return;

		var params = uW.Object.clone(uW.g_ajaxparams);
		var cityID = cid;
		var tileid = tid;
		params.tid=tid;
		params.cid=cid;
		params.x=x;
		params.y=y;
		new AjaxRequest(uW.g_ajaxpath + "ajax/abandonWilderness.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess:function(transport){
				var rslt=eval("("+transport.responseText+")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					t.error_code = 0;
					if (rslt.returningMarches) {
						var cities = Object.keys(rslt.returningMarches);
						for (var i = 0; i < cities.length; i++) {
							for (var j = 0; j < rslt.returningMarches[cities[i]].length; j++) {
								var cid = cities[i].split("c")[1];
								var mid = rslt.returningMarches[cities[i]][j];
								var march = Seed.queue_atkp["city" + cid]["m" + mid];
								if (march) {
									var marchtime = Math.abs(parseInt(march.destinationUnixTime) - parseInt(march.marchUnixTime));
									var ut = uW.unixtime();
									Seed.queue_atkp["city" + cid]["m" + mid].destinationUnixTime = ut;
									Seed.queue_atkp["city" + cid]["m" + mid].marchUnixTime = ut - marchtime;
									Seed.queue_atkp["city" + cid]["m" + mid].returnUnixTime = ut + marchtime;
									Seed.queue_atkp["city" + cid]["m" + mid].marchStatus = 8
								}
							}
						}
					}
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
					if (Object.keys(Seed.wilderness["city" + cityID]).length == 1) {
						Seed.wilderness["city" + cityID] = []
					} else	{
						delete Seed.wilderness["city"+cityID]["t"+tileid];
					}
				} else {
					if (rslt.error_code != 401) {
						t.error_code = rslt.error_code;
					}
				}
			},
			onFailure: function () {}
		});
	},

	Rounds : function (r, retry, CrestDataNum) {
		var t = Tabs.Crest;
		clearTimeout(t.timer);
		if (!Options.crestRunning) return;

		if (CrestData.length == 0)
			return;

		if (CrestDataNum >= CrestData.length)
			CrestDataNum = 0;

		if (CrestData[CrestDataNum].active==""+culang.mainActivate+"") {
			t.timer =setTimeout(function() { t.Rounds(1,0,parseInt(CrestDataNum+1)); },1000);
			return;
		}

		cityID = 'city' + CrestData[CrestDataNum].CrestCity;
		retry++;

		for (var k in Seed.wilderness[cityID] ){
			if (Seed.wilderness[cityID][k]['xCoord']==CrestData[CrestDataNum].X && Seed.wilderness[cityID][k]['yCoord']==CrestData[CrestDataNum].Y && t.error_code!=401) {
				t.abandonWilderness(Seed.wilderness[cityID][k]['tileId'],Seed.wilderness[cityID][k]['xCoord'],Seed.wilderness[cityID][k]['yCoord'],CrestData[CrestDataNum].CrestCity,t.Rounds,retry,CrestDataNum);
			}
		}
		
		if (parseInt(Seed.units[cityID]['unt1']) < CrestData[CrestDataNum].R1ST || 
				parseInt(Seed.units[cityID]['unt2']) < CrestData[CrestDataNum].R1MM || 
				parseInt(Seed.units[cityID]['unt3']) < CrestData[CrestDataNum].R1Scout || 
				parseInt(Seed.units[cityID]['unt4']) < CrestData[CrestDataNum].R1Pike || 
				parseInt(Seed.units[cityID]['unt5']) < CrestData[CrestDataNum].R1Sword || 
				parseInt(Seed.units[cityID]['unt6']) < CrestData[CrestDataNum].R1Arch || 
				parseInt(Seed.units[cityID]['unt7']) < CrestData[CrestDataNum].R1LC || 
				parseInt(Seed.units[cityID]['unt8']) < CrestData[CrestDataNum].R1HC || 
				parseInt(Seed.units[cityID]['unt9']) < CrestData[CrestDataNum].R1SW || 
				parseInt(Seed.units[cityID]['unt10']) < CrestData[CrestDataNum].R1Ball || 
				parseInt(Seed.units[cityID]['unt11']) < CrestData[CrestDataNum].R1Ram || 
				parseInt(Seed.units[cityID]['unt12']) < CrestData[CrestDataNum].R1Cat || 
				parseInt(Seed.units[cityID]['unt13']) < CrestData[CrestDataNum].R1BT || 
				parseInt(Seed.units[cityID]['unt14']) < CrestData[CrestDataNum].R1EX || 
				parseInt(Seed.units[cityID]['unt15']) < CrestData[CrestDataNum].R1SWa || 
				parseInt(Seed.units[cityID]['unt1']) < CrestData[CrestDataNum].R2ST || 
				parseInt(Seed.units[cityID]['unt2']) < CrestData[CrestDataNum].R2MM || 
				parseInt(Seed.units[cityID]['unt3']) < CrestData[CrestDataNum].R2Scout || 
				parseInt(Seed.units[cityID]['unt4']) < CrestData[CrestDataNum].R2Pike || 
				parseInt(Seed.units[cityID]['unt5']) < CrestData[CrestDataNum].R2Sword || 
				parseInt(Seed.units[cityID]['unt6']) < CrestData[CrestDataNum].R2Arch || 
				parseInt(Seed.units[cityID]['unt7']) < CrestData[CrestDataNum].R2LC || 
				parseInt(Seed.units[cityID]['unt8']) < CrestData[CrestDataNum].R2HC || 
				parseInt(Seed.units[cityID]['unt9']) < CrestData[CrestDataNum].R2SW || 
				parseInt(Seed.units[cityID]['unt10']) < CrestData[CrestDataNum].R2Ball || 
				parseInt(Seed.units[cityID]['unt11']) < CrestData[CrestDataNum].R2Ram || 
				parseInt(Seed.units[cityID]['unt12']) < CrestData[CrestDataNum].R2Cat ||
				parseInt(Seed.units[cityID]['unt13']) < CrestData[CrestDataNum].R2BT ||
				parseInt(Seed.units[cityID]['unt14']) < CrestData[CrestDataNum].R2EX ||
				parseInt(Seed.units[cityID]['unt15']) < CrestData[CrestDataNum].R2SWa) {
			if (CrestData.length == 1) {
				t.timer =setTimeout(function(){ t.Rounds(r,retry,CrestDataNum);},Options.Crestinterval*1000);
				return;
			} else
				t.timer =setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			return;
		}

		t.getAtkKnight(cityID);
		slots=0;

		for (z in Seed.queue_atkp[cityID]) {
			slots++;
		}
		if  (Seed.queue_atkp[cityID].toSource() == "[]")
			slots=0;

		slots=parseInt(slots)+parseInt(Options.CrestSlot); // protection slots
		t.getRallypointLevel(cityID);
		var add = 0;
		if (Seed.cityData.city[CrestData[CrestDataNum].CrestCity].isPrestigeCity) {
			add = 3;
		}
		switch (t.rallypointlevel) {
			case 12:
				t.rallypointlevel = t.rallypointlevel - 1;
			default:
				t.rallypointlevel = t.rallypointlevel + add;
				if (t.rallypointlevel <= slots) {
					if (CrestData.length == 1) {
						t.timer = setTimeout(function(){ t.Rounds(r,retry,CrestDataNum);},Options.Crestinterval*1000);
					} else {
						t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
					}
					return;
					break;
				}
		}
		
		if  (t.knt.toSource() == "[]") {
			t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
			return;
		}
		var kid = t.knt[0].ID;
		if (CrestData[CrestDataNum].R1ST == 0 && 
				CrestData[CrestDataNum].R1MM == 0 && 
				CrestData[CrestDataNum].R1Scout == 0 && 
				CrestData[CrestDataNum].R1Pike == 0 && 
				CrestData[CrestDataNum].R1Sword == 0 && 
				CrestData[CrestDataNum].R1Arch == 0 && 
				CrestData[CrestDataNum].R1LC == 0 && 
				CrestData[CrestDataNum].R1HC == 0 && 
				CrestData[CrestDataNum].R1SW == 0 && 
				CrestData[CrestDataNum].R1Ball == 0 && 
				CrestData[CrestDataNum].R1Ram == 0 &&
				CrestData[CrestDataNum].R1Cat == 0 &&
				CrestData[CrestDataNum].R1BT == 0 &&
				CrestData[CrestDataNum].R1EX == 0 &&
				CrestData[CrestDataNum].R1SWa == 0) {
			r=2;
		}else {
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			if (now > (parseInt(CrestData[CrestDataNum].lastRoundTwo) + 300)) { // 3 minutes entre les premi?res vagues 
				r=1;
			}
		}

		var troopCount = 0;
		switch(r) {
			case 1:
				if ((t.rallypointlevel-slots) < 2) {
					t.timer =setTimeout(function(){ t.Rounds(1,retry,(parseInt(CrestDataNum)+1));},Options.Crestinterval*1000);
					return;
				}
				var params 		= 	uW.Object.clone(uW.g_ajaxparams);
				params.cid		= 	CrestData[CrestDataNum].CrestCity;
				params.type		=	4;
				params.kid		= 	kid;
				params.xcoord 	= 	CrestData[CrestDataNum].X;
				params.ycoord 	= 	CrestData[CrestDataNum].Y;
				params.u1 		= 	CrestData[CrestDataNum].R1ST; troopCount += parseInt(params.u1);
				params.u2 		= 	CrestData[CrestDataNum].R1MM; troopCount += parseInt(params.u2);
				params.u3 		= 	CrestData[CrestDataNum].R1Scout; troopCount += parseInt(params.u3);
				params.u4 		= 	CrestData[CrestDataNum].R1Pike; troopCount += parseInt(params.u4);
				params.u5 		= 	CrestData[CrestDataNum].R1Sword; troopCount += parseInt(params.u5);
				params.u6 		= 	CrestData[CrestDataNum].R1Arch; troopCount += parseInt(params.u6);
				params.u7 		= 	CrestData[CrestDataNum].R1LC; troopCount += parseInt(params.u7);
				params.u8 		= 	CrestData[CrestDataNum].R1HC; troopCount += parseInt(params.u8);
				params.u9 		= 	CrestData[CrestDataNum].R1SW; troopCount += parseInt(params.u9);
				params.u10 		= 	CrestData[CrestDataNum].R1Ball; troopCount += parseInt(params.u10);
				params.u11 		= 	CrestData[CrestDataNum].R1Ram; troopCount += parseInt(params.u11);
				params.u12 		= 	CrestData[CrestDataNum].R1Cat; troopCount += parseInt(params.u12);
				params.u13 		= 	CrestData[CrestDataNum].R1BT; troopCount += parseInt(params.u13);
				params.u14 		= 	CrestData[CrestDataNum].R1EX; troopCount += parseInt(params.u14);
				params.u15 		= 	CrestData[CrestDataNum].R1SWa; troopCount += parseInt(params.u15);
				if (troopCount > 0){
					t.sendMarch(params,t.Rounds,r,retry, CrestDataNum);
				}else{
					//Log
					var rep = {
						'city' : Cities.byID[params.cid].name,
						'koords' : params.xcoord + "," +params.ycoord,
						'wave' : r,
						'error' : '<span style="color:red;">{no troops}</span>',
					};
					actionLog(culang.tabLabelCrest,culang.crestmsgError.mreplace(rep));
				}
				break;
			default:
				var params 		= 	uW.Object.clone(uW.g_ajaxparams);
				params.cid		= 	CrestData[CrestDataNum].CrestCity;
				params.type		= 	4;
				params.kid		= 	kid;
				params.xcoord 	= 	CrestData[CrestDataNum].X;
				params.ycoord 	= 	CrestData[CrestDataNum].Y;
				params.u1 		= 	CrestData[CrestDataNum].R2ST; troopCount += parseInt(params.u1);
				params.u2 		= 	CrestData[CrestDataNum].R2MM; troopCount += parseInt(params.u2);
				params.u3 		= 	CrestData[CrestDataNum].R2Scout; troopCount += parseInt(params.u3);
				params.u4 		= 	CrestData[CrestDataNum].R2Pike; troopCount += parseInt(params.u4);
				params.u5 		= 	CrestData[CrestDataNum].R2Sword; troopCount += parseInt(params.u5);
				params.u6 		= 	CrestData[CrestDataNum].R2Arch; troopCount += parseInt(params.u6);
				params.u7 		= 	CrestData[CrestDataNum].R2LC; troopCount += parseInt(params.u7);
				params.u8 		= 	CrestData[CrestDataNum].R2HC; troopCount += parseInt(params.u8);
				params.u9 		= 	CrestData[CrestDataNum].R2SW; troopCount += parseInt(params.u9);
				params.u10 		= 	CrestData[CrestDataNum].R2Ball; troopCount += parseInt(params.u10);
				params.u11 		= 	CrestData[CrestDataNum].R2Ram; troopCount += parseInt(params.u11);
				params.u12 		= 	CrestData[CrestDataNum].R2Cat; troopCount += parseInt(params.u12);
				params.u13 		= 	CrestData[CrestDataNum].R2BT; troopCount += parseInt(params.u13);
				params.u14 		= 	CrestData[CrestDataNum].R2EX; troopCount += parseInt(params.u14);
				params.u15 		= 	CrestData[CrestDataNum].R2SWa; troopCount += parseInt(params.u15);
				if (troopCount > 0){
					t.sendMarch(params,t.Rounds,r,retry, CrestDataNum);
				}else{
					//Log
					var rep = {
						'city' : Cities.byID[params.cid].name,
						'koords' : params.xcoord + "," +params.ycoord,
						'wave' : r,
						'error' : '<span style="color:red;">{no troops}</span>',
					};
					actionLog(culang.tabLabelCrest,culang.crestmsgError.mreplace(rep));
				}
				break;
		}

	},

	toggleCrestState: function(obj) {
		var t = Tabs.Crest;
		obj = ById('Cresttoggle');
		if (Options.crestRunning == true) {
			Options.crestRunning = false;
			if (obj) obj.value = culang.tabLabelCrest+" = "+culang.buttonOFF;
			saveOptions();
		} else {
			Options.crestRunning = true;
			if (obj) obj.value = culang.tabLabelCrest+" = "+culang.buttonON;
			Options.Creststatus={1101:0,1102:0,1103:0,1104:0,1105:0,1106:0,1107:0,1108:0,1109:0,1110:0,1111:0,1112:0,1113:0,1114:0,1115:0,9:0,36:0,37:0,38:0,55:0,57:0,261:0,262:0,271:0,272:0,351:0,361:0,362:0,911:0,3000:0,3001:0,3002:0,3003:0,3007:0,3008:0,3009:0,3011:0,931:0,932:0,285:0,};
			for (crest in Options.Creststatus) {
				owned = Seed.items['i'+crest];
				if (owned == undefined) {
					owned=0;
				}
				Options.Creststatus[crest] = owned;
				Options.Crest1Count = 0;
				Options.Crest2Count = 0;
			}
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			Options.LastCrestReport = now;
			saveOptions();
			t.timer =setTimeout(function(){ t.Rounds(1,0,0);}, 1000);
		}
	},
	sendCrestReportNow: function(){
		var t = Tabs.Crest;
		var now = new Date().getTime()/1000.0;
		now = now.toFixed(0);
		var total = 0;
		var wildtype = '';

		var message = ''+culang.crestReportHead+' %0A';
		message += '%0A '+culang.crestReportCrestFound+' %0A';

		for (crest in Options.Creststatus) {
			owned = Seed.items['i'+crest];
			if (owned == undefined)
				owned =	0;
			if ((owned - Options.Creststatus[crest]) > 0)
				message	+= 	'<DIV><B>' + uW.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A </b></div>';
			total += (owned - Options.Creststatus[crest]);
			Options.Creststatus[crest] = owned;

		}
		message += '%0A '+culang.mainTime+': ' + timestr(now-Options.LastCrestReport) + '%0A'
		message += '%0A  '+culang.crestReportCrestTotal+'  '+ total +' '+culang.crestReportCrestTotal2+'%0A';
		message += '%0A '+culang.crestReportFirstWave+' '+ Options.Crest1Count +' '+culang.crestReportFirstWave2+' %0A';
		message += ''+culang.crestReportSecondWave+' '+ Options.Crest2Count +' '+culang.crestReportSecondWave2+' %0A';

		Options.Crest1Count = 0;
		Options.Crest2Count = 0;
		Options.Crest3Count = 0;
		Options.Crest4Count = 0;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.emailTo = Seed.player['name'];
		params.subject = culang.crestReport;
		params.message = message;
		params.requestType = "COMPOSED_MAIL";
		new AjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (message) {
				var rslt = eval("(" + message.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					Options.LastCrestReport = now;
				} else {
				}
			},
			onFailure: function () {
			},
		});
		saveOptions();
	},
	sendCrestReport: function(){
		if(!Options.crestreport || !CrestOptions.Running)
			return;

		var t = Tabs.Crest;
		var now = new Date().getTime()/1000.0;
		now = now.toFixed(0);

		if (now < (parseInt(Options.LastCrestReport)+(Options.CrestMsgInterval*60*60)))
			return;

		var total = 0;
		var wildtype = 	'';

		var message = ''+culang.crestReportHead+' %0A';
		message += '%0A '+culang.crestReportCrestFound+' %0A';

		for (crest in Options.Creststatus) {
			owned = Seed.items['i'+crest];
			if (owned == undefined)
				owned =	0;
			if ((owned - Options.Creststatus[crest]) > 0)
				message	+= 	'<DIV><B>' + uW.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A </b></div>';
			else
				message	+= 	uW.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A';

			total += (owned - Options.Creststatus[crest]);
			Options.Creststatus[crest] = owned;
		}

		message += '%0A '+culang.crestReportCrestTotal+' '+ total +' '+culang.crestReportCrestTotal2+' %0A';
		message += '%0A '+culang.crestReportFirstWave+' '+ Options.Crest1Count +' '+culang.crestReportFirstWave2+' %0A';
		message += ''+culang.crestReportSecondWave+' '+ Options.Crest2Count +' '+culang.crestReportSecondWave2+' %0A';

		Options.Crest1Count = 0;
		Options.Crest2Count = 0;

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.emailTo = Seed.player['name'];
		params.subject = culang.crestReport;
		params.message = message;
		params.requestType = "COMPOSED_MAIL";

		new AjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (message) {
				var rslt = eval("(" + message.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					Options.LastCrestReport = now;
				}
			},
			onFailure: function () {
			},
		});

		saveOptions();
	},


	hide : function (){
		var t = Tabs.Crest;
	},

	show : function (){
	},
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Transport.js">
//	
//	   KOC POWER - TABS TRANSPORT										        
//	


Tabs.Transport = {
	tabOrder: TabOptions.toTransport,
	tabLabel: culang.mainTransport,
	cont : null,
	displayTimer : null,
	state : null,
	curTabBut : null,
	curTabName : null,
	sourceCity : {},
	destinationCity : {},
	rows : [],
	timer: null,
	timer2: null,
	traderState: [],
	reapproState: [],
	lTR: [],
	tradeRoutes: [],
	checkdotradetimeout: null,
	checkdoreapprotimeout: null,
	count:0,
	check:false,
	show : function (){
		var t = Tabs.Transport;
		if (document.getElementById ('maparea_map').style.display!="none") {
			if (t.destinationCityx) {
				t.destinationCityx.value = document.getElementById ('mapXCoor').value;
				t.destinationCityy.value = document.getElementById ('mapYCoor').value;
			}
		}
		if (t.curTabBut) {
			var but=t.curTabBut;
			t.show2();
		}
	},
	hide : function (){
		var t = Tabs.Transport;
		clearTimeout (t.displayTimer);
		clearTimeout (t.timer);
	},

	init : function (div){
		var t = Tabs.Transport;
		uW.Ksestimeres = t.estimerRes;
		t.traderState = {running: false,};
		t.reapproState = {running: false,city:-1,unit:9,mini:1000};
		t.readTraderState();
		t.readReapproState();
		t.readTradeRoutes();
		t.e_tradeRoutes();

		window.addEventListener('unload', t.onUnload, false);
		t.checkAutoRoutes();
		t.cont = div;
		t.cont.innerHTML = '<TABLE class=pdxTab align=center><TR><TD><INPUT class=ksMSubtab ID=BoTrpSubM type=submit value="'+culang.transportTabLabel+'"></td>\
             <TD><INPUT class=ksMSubtab ID=BoTrpSubA type=submit  value="'+culang.transportAutoTabLabel+'"></td><TD><INPUT class=ksMSubtab ID=BoTrpSubR type=submit  value="'+culang.transportSupplyTabLabel+'"></td></tr></table>\
         <DIV id="BoTrpOutput" style="margin-top:5px; background-color:white; max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
		t.TransportDiv = ById('BoTrpOutput');
		ById('BoTrpSubA').addEventListener('click', e_butSubtab, false);
		ById('BoTrpSubM').addEventListener('click', e_butSubtab, false);
		ById('BoTrpSubR').addEventListener('click', e_butSubtab, false);

		changeSubtab (ById('BoTrpSubM'));

		function e_butSubtab (evt){
			changeSubtab (evt.target);
		}

		function changeSubtab (but){
			if (but == t.curTabBut)
				return;
			if (t.curTabBut){
				t.curTabBut.className='ksMSubtab';
				t.curTabBut.disabled=false;
			}
			t.curTabBut = but;
			but.className='ksMSubtab ksMSubtabSel';
			but.disabled=true;
			t.curTabName = but.id.substr(8);
			t.show2();
		}
		var final = 0;
		if (t.reapproState.city>=0) {
			for(var i=0; i<Cities.numCities; i++) {
				var x2 = parseInt(Cities.cities[i].x);
				var x1 = parseInt(Cities.cities[t.reapproState.city].x);
				var y2 = parseInt(Cities.cities[i].y);
				var y1 = parseInt(Cities.cities[t.reapproState.city].y);
				var dist = distance (x1, y1, x2, y2);
				var m = estETA(dist,t.reapproState.unit,Cities.cities[t.reapproState.city].id,1);
				if (m.friendETA>final)
					final=m.friendETA;
			}
			//Options.reapprointerval = parseInt(final/60*2+10);
		}
	},
	show2 : function (){
		var t = Tabs.Transport
		t.state = null;
		clearTimeout (t.displayTimer);
		clearTimeout (t.timer);
		if (t.curTabName == 'M')
			t.showManuel();
		else  if (t.curTabName == 'R')
			t.showReappro();
		else {
			t.showAuto();
			t.showTimer();
		}
		if (t.reapproState.running == true) {
			t.checkdoreapprotimeout = setTimeout(t.actionreappro, 10000);
		}
		
	},
	showTimer: function() {
		var t = Tabs.Transport;
		t.updateTroops();
		t.updateResources();
		t.timer = setTimeout (t.showTimer, 1000);
	},
	showReappro: function () {
		var t = Tabs.Transport;
		var m = '<DIV id=pbSupplyTab class=pdxStat>'+culang.transportSupplyHead+' - <input type=button value="?" id=boaideappro class=buttonHelp></div><TABLE id=pbtraderfunctions width=100% height=0% class=pdxTab><TR align="center"><TD><span title="+ 10 '+culang.mainMinutes+'"><b>'+culang.mainIntervall+'</b>: <INPUT id=pbreapprointerval type=text size=2 value="'+Options.reapprointerval+'"\> '+culang.mainMinutes+'</td><td><input type=button value="'+culang.buttonSave+'" id="boReappro"></td>';
		if (t.reapproState.running == false) {
			m += '<TD><INPUT id=boReapproState type=submit value="'+culang.shrsupply+' = '+culang.buttonOFF+' "></td>';
		} else {
			m += '<TD><INPUT id=boReapproState type=submit value="'+culang.shrsupply+' = '+culang.buttonON+' "></td>';
		}
		m += '</tr></table>';
		m += '<DIV id=pbReapproDivDRoute class=pdxStat>'+culang.transportSupplyHeadSettings+'</div>';
		m += '<TABLE id=pbaddReapproroute width=95% height=0% class=pdxTab><TR align="left">';
		m += '<TR align="left"><TD colspan=2><b>'+culang.mainCastle+'</b>:</td> <TD colspan=3><DIV style="margin-bottom:10px;"><span id=borescity></span></div></td><td colspan=4><b>'+culang.mainTroops+'</b>: <select id="KsApproUnit"><option value=9>'+culang.shrsupplywagon+'</option><option value=7>'+culang.shrcavalry+'</option><option value=8>'+culang.heavycavalry+'</option></select>&nbsp; '+culang.shortMin+': <input type=text size=5 value="0" id=KsApproMin></td></tr>';

		var Types = ['gold','food','wood','stone','iron','aetherstone'];

		m += '<TR align="left"><td colspan=2></td>';
		for (var y=0; y< Seed.cities.length;y++)
			m += '<td><b><u>'+Seed.cities[y][1]+'</u></b></td>';
		for (var i=0;i<=5;i++) {
			m += '</tr><tr><td align=center valign=middle rowspan=2><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/'+Types[i]+'_30.png"></td><td></td>';
			for (var y=0; y< Seed.cities.length;y++)
				m += '<td><span id="ReappRec_'+y+'_'+i+'"></span></td>';
			m += '</tr><tr><td>'+culang.transportSupplyKeep+'</td>';
			for (var y=0; y< Seed.cities.length;y++)
				m += '<td><input id="ReappRes_'+y+'_'+i+'" type=text size=10 maxlength=12 value=0></td>';
			m +='</tr>';
		}
		m += '</table><div style="font-size:10px; color:#555; text-align:center;"> '+culang.transportValue+' </div>';
		t.TransportDiv.innerHTML = m;
		if (t.reapproState.city==undefined ||t.reapproState.city==-1) {

			t.reapproState.city=0;
		}
		ById('boaideappro').addEventListener('click', function(){
			window.open(homePage+" ");
		} , false);
		t.reacp = new CdispCityPicker ('botrader', ById('borescity'), true, t.updateResources2, t.reapproState.city);
		ById('KsApproMin').addEventListener('change', function(){
			t.reapproState.mini = ById('KsApproMin').value;
			t.saveReappro();
		}, false);
		ById('boReapproState').addEventListener('click', function(){t.toggleReapproState(this);}, false);
		ById('boReappro').addEventListener('click', function(){t.saveReappro();}, false);

		ById('pbreapprointerval').addEventListener('change', function(){
			if (isNaN(ById('pbreapprointerval').value)) { 
				ById('pbreapprointerval').value=60;
			}
			Options.reapprointerval = parseInt(ById('pbreapprointerval').value);
			saveOptions();
		}, false);

		//ById('KsRecupReappro').addEventListener('click', function(){t.RecupReappro();}, false);
		ById('KsApproUnit').value = t.reapproState.unit;
		ById('KsApproMin').value = parseIntNan(t.reapproState.mini);
		ById('KsApproUnit').addEventListener('change', function(){
			t.reapproState.unit = ById('KsApproUnit').value;
			t.saveReappro();

		}, false);

		t.updateResources2();
	},
	RecupReappro:function() {
		var t = Tabs.Transport;
		var r = t.tradeRoutes;
		for (var y=0; y< Seed.cities.length;y++) {
			for (var i=0;i<(r.length);i++) {
				if (parseInt(Seed.cities[y][0]) == r[i].city) {
					ById('ReappRes_'+y+'_0').value=r[i].target_Gold;
					ById('ReappRes_'+y+'_1').value=r[i].target_Food;
					ById('ReappRes_'+y+'_2').value=r[i].target_Wood;
					ById('ReappRes_'+y+'_3').value=r[i].target_Stone;
					ById('ReappRes_'+y+'_4').value=r[i].target_Ore;
					ById('ReappRes_'+y+'_5').value=r[i].target_Astone;

				}
			}
		}
		t.saveReappro();
	},
	saveReapproState: function(){
		var t = Tabs.Transport;
		var serverID = getServerId();
		GM_setValue('reapproState_' + serverID, JSON2.stringify(t.reapproState));
	},
	saveReappro:function() {
		var t = Tabs.Transport;
		for (var y=0; y< Seed.cities.length;y++) {
			t.reapproState['ReappRes_'+y+'_0'] = parseIntNan(ById('ReappRes_'+y+'_0').value);
			for (var i=1;i<=5;i++) {
				t.reapproState['ReappRes_'+y+'_'+i] = parseIntNan(ById('ReappRes_'+y+'_'+i).value);
			}
		}
		t.saveReapproState();
	},
	readReapproState: function(){
		var t = Tabs.Transport;
		var serverID = getServerId();
		s = GM_getValue('reapproState_' + serverID);
		if (s != null) {
			state = JSON2.parse(s);
			for (k in state)
				t.reapproState[k] = state[k];
		}
	},
	toggleReapproState: function(obj){
		var t = Tabs.Transport;
		obj = ById('boReapproState');
		if (t.reapproState.running == true) {
			t.reapproState.running = false;
			if (obj)  obj.value = ""+culang.shrsupply+" = "+culang.buttonOFF;
			clearTimeout(t.checkdoreapprotimeout);
		}
		else {
			t.reapproState.running = true;
			if (obj) obj.value = ""+culang.shrsupply+" = "+culang.buttonON;
			t.actionreappro();
		}
	},
	retry:0,
	nbcity:-1,
	actionreappro:function() {
		var t = Tabs.Transport;
		t.nbcity++;
		if (t.reapproState.running == false) {
			clearTimeout(t.checkdoreapprotimeout);
			return;
		}
		if (t.nbcity==t.reapproState.city)
			t.nbcity++;
		var tempsprochainevisite = 10000;
		if ((Seed.cities.length-1)<t.nbcity) {
			tempsprochainevisite = Options.reapprointerval*60*1000;
			t.nbcity=-1;
		} else {
			var besoin=[0,0,0,0,0,0];
			var stock=[0,0,0,0,0,0];
			qtemin = parseIntNan(t.reapproState['ReappRes_'+t.nbcity+'_0']);
			qtest = parseIntNan(Seed.citystats["city" + Seed.cities[t.nbcity][0]]['gold'][0]);
			if (qtest<qtemin)
				besoin[0] = parseInt(qtemin - qtest);
			stock[0] = parseIntNan(Seed.citystats["city" + Seed.cities[t.reapproState.city][0]]['gold'][0]);
			for (var i=1;i<=5;i++) {
				qtemin = parseIntNan(t.reapproState['ReappRes_'+t.nbcity+'_'+i]);
				if(i==5) {
					qtest = parseInt(Seed.resources["city" + Seed.cities[t.nbcity][0]]['rec'+i][0]);
					qtstock = parseInt(Seed.resources["city" + Seed.cities[t.reapproState.city][0]]['rec'+i][0]);
				}else {
					qtest = parseInt(Seed.resources["city" + Seed.cities[t.nbcity][0]]['rec'+i][0]/3600);
					qtstock= parseInt(Seed.resources["city" + Seed.cities[t.reapproState.city][0]]['rec'+i][0]/3600);
				}
				if (qtest<qtemin)
					besoin[i] = parseInt(qtemin - qtest);
				stock[i] = qtstock;
			}
			var RInfo = getRallypointInfo(Cities.cities[t.reapproState.city].id);
			if(RInfo.usedSlots >= RInfo.maxMarches){
				actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+" <font color=red>"+culang.transportSupplyLogFullRP+"</font>");
				return;
			}
			if (besoin[0]>0 || besoin[1]>0|| besoin[2]>0 || besoin[3]>0 || besoin[4]>0 || besoin[5]>0) {
				//actionLog(""+culang.mainSupply+"","Transport von: "+Cities.cities[t.reapproState.city].name+" nach: "+Cities.cities[t.nbcity].name+" : pierre:" + besoin[3] +"<"+stock[3]+" && mine: "+besoin[4]+"<"+stock[4]+"");
				if (besoin[0]<=stock[0] && besoin[1]<=stock[1] && besoin[2]<=stock[2] && besoin[3]<=stock[3] && besoin[4]<=stock[4] && besoin[5]<=stock[5]) {
					var unit = 'unt' + t.reapproState.unit;
					Troops = parseInt(Seed.units['city' + Seed.cities[t.reapproState.city][0]][unit]);
					var untid=t.reapproState.unit;
					var LoadUnit = getMaxLoad(untid,1);
					TroopsNeeded = (besoin[0] + besoin[1] + besoin[2] + besoin[3] + besoin[4] + (besoin[5]*5))  / LoadUnit;
					TroopsNeeded = TroopsNeeded.toFixed(0);
					if (TroopsNeeded < ((besoin[0] + besoin[1] + besoin[2] + besoin[3] + besoin[4] + (besoin[5]*5))  / LoadUnit )) TroopsNeeded++;
					var RInfo = getRallypointInfo(Seed.cities[t.reapproState.city][0]);
					if (parseInt(TroopsNeeded) > RInfo.maxMarchSize){
						TroopsNeeded = RInfo.maxMarchSize;
						var lemax=LoadUnit*TroopsNeeded;
						var totalb=lemax;
						for (var i=1;i<=5;i++) {
							if (besoin[i]>=totalb)
								besoin[i]=totalb;
							totalb=totalb-besoin[i];
						}
					}
					if (parseIntNan(TroopsNeeded)<=parseIntNan(Troops) && parseIntNan(TroopsNeeded)>=parseIntNan(t.reapproState.mini)) {
						var city = Seed.cities[t.reapproState.city][0];
						var params = uW.Object.clone(uW.g_ajaxparams);
						params.gold =besoin[0];
						params.r1 =besoin[1];
						params.r2 =besoin[2];
						params.r3 =besoin[3];
						params.r4 =besoin[4];
						params.r5 =besoin[5];
						params.kid = 0;
						params.type = "1";
						params.cid=city;
						switch (unit){
							case 'unt1': params.u1 = TroopsNeeded;break;
							case 'unt2': params.u2 = TroopsNeeded;break;
							case 'unt3': params.u3 = TroopsNeeded;break;
							case 'unt4': params.u4 = TroopsNeeded;break;
							case 'unt5': params.u5 = TroopsNeeded;break;
							case 'unt6': params.u6 = TroopsNeeded;break;
							case 'unt7': params.u7 = TroopsNeeded;break;
							case 'unt8': params.u8 = TroopsNeeded;break;
							case 'unt9': params.u9 = TroopsNeeded;break;
							case 'unt10': params.u10 = TroopsNeeded;break;
							case 'unt11': params.u11 = TroopsNeeded;break;
							case 'unt12': params.u12 = TroopsNeeded;break;
							case 'unt13': params.u13 = TroopsNeeded;break;
							case 'unt14': params.u14 = TroopsNeeded;break;
							case 'unt15': params.u15 = TroopsNeeded;break;
						}
						params.xcoord = Seed.cities[t.nbcity][2];
						params.ycoord = Seed.cities[t.nbcity][3];

						new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
							method: "post",
							parameters: params,
							loading: true,
							onSuccess: function (transport) {
								var rslt = eval("(" + transport.responseText + ")");
								if (rslt.ok) {
									var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
									var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
									var ut = uW.unixtime();
									var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
									for(i = 0; i <= unitsarr.length; i++){
										if(params["u"+i]){
											unitsarr[i] = params["u"+i];
										}
									}
									var resources=new Array();
									resources[0] = params.gold;
									for(i=1; i<=4; i++){
										resources[i] = params["r"+i];
									}
									var currentcityid = params.cid;
									uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
											 
									if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
									actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+" - "+TroopsNeeded+" "+uW.unitcost[unit][0]);
								} else {
									actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+" <font color=red>" + transport.responseText +"</font>");
									t.retry++;
									if (t.retry>4) {
										t.retry=0;
									}else {
										setTimeout(function() {t.nbcity--;t.actionreappro();},4000);
									}
								}
							},

							onFailure: function (rslt) {
								if (rslt.user_action) {
									actionLog(""+culang.mainSupply+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
									new CdialogCancelContinue('<SPAN class=boldRed>'+culang.supplyCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);

								} else {
									actionLog(""+culang.mainSupply+"","<font color=red>" + rslt.responseText +"</font>");
								}
							}

						});
					} else {
						actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+": "+culang.transportSupplyLogNoTroops+"");
					}
				} else {
					actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+": "+culang.transportSupplyLogNoRes+"");
				}
			}
		}
		t.checkdoreapprotimeout = setTimeout(function() { t.actionreappro();}, tempsprochainevisite);
	},
	showAuto: function() {
		var t = Tabs.Transport;
		var m = '<DIV id=pbAutoTransportTab class=pdxStat>'+culang.transportAutoHead+'</div><TABLE id=pbtraderfunctions width=100% height=0% class=pdxTab><TR align="center"><TD><b>'+culang.mainIntervall+'</b>: <INPUT id=pbtransportinterval type=text size=4 value="'+Options.transportinterval+'"\> '+culang.mainMinutes+'</td><TD>'+culang.transportAutoMinTroops+' <INPUT id=pbminwagons type=text size=2 value="'+Options.minwagons+'"\></td><TD><INPUT id=pbShowRoutes type=submit value="'+culang.mainShowRoutes+'"></td>';
		if (t.traderState.running == false) {
			m += '<TD><INPUT id=pbTraderState type=submit value="'+culang.mainTransport+' = '+culang.buttonOFF+' "></td>';
		} else {
			m += '<TD><INPUT id=pbTraderState type=submit value="'+culang.mainTransport+' = '+culang.buttonON+' "></td>';
		}
		m += '</tr></table></div>';

		m += '<DIV id=pbTraderDivDRoute class=pdxStat>'+culang.transportAutoAddRouteHead+'</div>';
		m += '<TABLE id=pbaddtraderoute width=95% height=0% class=pdxTab><TR align="left">';
		m += '<TR align="left"><TD><b>'+culang.mainCastle+'</b>:</td> <TD colspan=4><DIV style="margin-bottom:10px;"><span id=ptrescity></span></div></td></tr>';

		m += '<TR align="left">';
		m += '<TD><b>'+culang.mainTarget+'</b>:</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptcityTo></span></div></td>';
		m += '<TD>'+culang.transportOrTargetCoord+'</td>';
		m += '<TD>X:<INPUT id=ptcityX type=text size=3\></td>';
		m += '<TD>Y:<INPUT id=ptcityY type=text size=3\></td></tr>';
		m += '<TABLE id=pbaddtraderoute height=0% class=pdxTab><TR align="left">';
		m += '<TD width=75px><B>'+culang.transportAutoTroopType+'</b>:</td><TD width=150px><SELECT id="TransportTroop">';
		for (y in uW.unitcost) m+='<option value="'+y+'">'+uW.unitcost[y][0]+'</option>';
		m+='</select></td><TD width=75px>'+culang.transportAutoTroopAvailable+'&nbsp;</td><TD id=TroopAmount align=left width=75px></td>';
		m+='<TD width=75px>'+culang.transportAutoTroopAvailableCarry+'&nbsp;</td><TD id=CarryAmount align=left width=75px></td>';
		m += '<TR><TD >'+culang.mainTroops+': </td><TD><INPUT id=TroopsToSend type=text size=6 maxlength=6 value="0">&nbsp;&nbsp;<INPUT id=MaxTroops type=submit value="'+culang.buttonMax+'"></td>';
		m += '<TD width=50px><INPUT id=FillInMax type=submit value="<----"></td>';
		m +='<TD id=Calc colspan=3></td></tr>';
		m += '<TABLE id=pbaddtraderoute height=0% class=pdxTab><TR align="center">';
		m += '<TD width=5%><img src="'+IMGfood30+'"></td>';
		m += '<TD id=TransRec1 align=right width=110px></td>';
		m += '<TD id=HaveRec1 align=right width=110px></td>';
		m += '<TD width=55px align=right><INPUT id=pbshipFood type=checkbox unchecked=true\></td>';
		m += '<TD width=180px  align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountFood type=text size=11 maxlength=12 value="0" disabled=true\></td>';
		m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountFood type=text size=11 maxlength=12 value="0"\></td>';
		m += '<TD width=50px><INPUT id=MaxFood type=submit value="'+culang.buttonMax+'"></td></tr>';
		m += '<TR align="center">';
		m += '<TD width=5%><img src="'+IMGwood30+'"></td>';
		m += '<TD id=TransRec2 align=right width=110px></td>';
		m += '<TD id=HaveRec2 align=right width=110px></td>';
		m += '<TD width=55px align=right><INPUT id=pbshipWood type=checkbox unchecked=true\></td>';
		m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountWood type=text size=11 maxlength=12 value="0" disabled=true\></td>';
		m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountWood type=text size=11 maxlength=12 value="0"\></td>';
		m += '<TD width=50px><INPUT id=MaxWood type=submit value="'+culang.buttonMax+'"></td></tr>';
		m += '<TR align="center">';
		m += '<TD width=5%><img src="'+IMGstone30+'"></td>';
		m += '<TD id=TransRec3 align=right width=110px></td>';
		m += '<TD id=HaveRec3 align=right width=110px></td>';
		m += '<TD width=55px align=right><INPUT id=pbshipStone type=checkbox unchecked=true\></td>';
		m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountStone type=text size=11 maxlength=12 value="0" disabled=true\></td>';
		m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountStone type=text size=11 maxlength=12 value="0"\></td>';
		m += '<TD width=50px><INPUT id=MaxStone type=submit value="'+culang.buttonMax+'"></td></tr>';
		m += '<TR align="center">';
		m += '<TD width=5%><img src="'+IMGiron30+'"></td>';
		m += '<TD id=TransRec4 align=right width=110px></td>';
		m += '<TD id=HaveRec4 align=right width=110px></td>';
		m += '<TD width=55px align=right><INPUT id=pbshipOre type=checkbox unchecked=true\></td>';
		m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountOre type=text size=11 maxlength=12 value="0" disabled=true\></td>';
		m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountOre type=text size=11 maxlength=12 value="0"\></td>';
		m += '<TD width=50px><INPUT id=MaxOre type=submit value="'+culang.buttonMax+'"></td></tr>';
		m += '<TR align="center">';
		m += '<TD width=5%><img src="'+IMGastone30+'"></td>';
		m += '<TD id=TransRec5 align=right width=110px></td>';
		m += '<TD id=HaveRec5 align=right width=110px></td>';
		m += '<TD width=55px align=right><INPUT id=pbshipAstone type=checkbox unchecked=true\></td>';
		m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountAstone type=text size=11 maxlength=12 value="0" disabled=true\></td>';
		m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountAstone type=text size=11 maxlength=12 value="0"\></td>';
		m += '<TD width=50px><INPUT id=MaxAstone type=submit value="'+culang.buttonMax+'"></td></tr>';
		m += '<TR align="center">';
		m += '<TD width=5%><img src="'+IMGgold30+'"></td>';
		m += '<TD id=TransGold align=right width=110px></td>';
		m += '<TD id=HaveGold align=right width=110px></td>';
		m += '<TD width=55px align=right><INPUT id=pbshipGold type=checkbox unchecked=true\></td>';
		m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountGold type=text size=11 maxlength=12 value="0" disabled=true\></td>';
		m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountGold type=text size=11 maxlength=12 value="0"\></td>';
		m += '<TD width=50px><INPUT id=MaxGold type=submit value="'+culang.buttonMax+'"></td></tr>';

		m += '</table>';

		m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRoute type=submit value="'+culang.transportAutoAddRoute+'"><INPUT id=pbManualSend type=submit value="'+culang.transportButton+'"></div><div style="font-size:10px; color:#555; text-align:center;"> '+culang.transportValue+' </div>';
		m += '<DIV id=errorSpace></div>'

		t.TransportDiv.innerHTML = m;

		ById('TransportTroop').value = 'unt9';

		t.tcp = new CdispCityPicker ('pttrader', ById('ptrescity'), true, t.updateResources, 0);
		t.tcpto = new CdispCityPicker ('pttraderTo', ById('ptcityTo'), true, t.clickCitySelect).bindToXYboxes(document.getElementById ('ptcityX'), document.getElementById ('ptcityY'));


		ById('TransportTroop').addEventListener('change', function(){t.updateTroops();}, false);
		ById('pbTraderState').addEventListener('click', function(){t.toggleTraderState(this);}, false);
		ById('pbSaveRoute').addEventListener('click', function(){t.addTradeRoute();}, false);
		ById('pbManualSend').addEventListener('click', function(){t.ManualTransport();}, false);
		ById('pbShowRoutes').addEventListener('click', function(){t.showTradeRoutes();}, false);
		ById('FillInMax').addEventListener('click', function(){ById('TroopsToSend').value = t.TroopsNeeded;}, false);

		ById('MaxTroops').addEventListener('click', function(){
			var RInfo = getRallypointInfo(t.tcp.city.id);
			if (RInfo.maxMarchSize > t.Troops) ById('TroopsToSend').value = t.Troops;
				else ById('TroopsToSend').value = RInfo.maxMarchSize;
		}, false);
		ById('MaxFood').addEventListener('click', function(){
			t.Food = 0;
			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
			ById('pbtradeamountFood').value = (parseInt(input) <= parseIntCommas(ById('TransRec1').innerHTML))?input:parseIntCommas(ById('TransRec1').innerHTML);
		}, false);
		ById('MaxWood').addEventListener('click', function(){
			t.Wood = 0;
			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
			ById('pbtradeamountWood').value = (parseInt(input) <= parseIntCommas(ById('TransRec2').innerHTML))?input:parseIntCommas(ById('TransRec2').innerHTML);
		}, false);
		ById('MaxStone').addEventListener('click', function(){
			t.Stone = 0;
			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
			ById('pbtradeamountStone').value = (parseInt(input) <= parseIntCommas(ById('TransRec3').innerHTML))?input:parseIntCommas(ById('TransRec3').innerHTML);
		}, false);
		ById('MaxOre').addEventListener('click', function(){
			t.Ore = 0;
			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
			ById('pbtradeamountOre').value = (parseInt(input) <= parseIntCommas(ById('TransRec4').innerHTML))?input:parseIntCommas(ById('TransRec4').innerHTML);
		}, false);
		ById('MaxGold').addEventListener('click', function(){
			t.Gold = 0;
			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
			ById('pbtradeamountGold').value = (parseInt(input) <= parseIntCommas(ById('TransGold').innerHTML))?input:parseIntCommas(ById('TransGold').innerHTML);
		}, false);
		ById('MaxAstone').addEventListener('click', function(){
			t.Astone = 0;
			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
			ById('pbtradeamountAstone').value = (parseInt(input) <= parseIntCommas(ById('TransRec5').innerHTML))?input:parseIntCommas(ById('TransRec5').innerHTML);
		}, false);

		ById('pbtransportinterval').addEventListener('keyup', function(){
			if (isNaN(ById('pbtransportinterval').value)){ ById('pbtransportinterval').value=60 ;}
			Options.transportinterval = ById('pbtransportinterval').value;
			saveOptions();
		}, false);

		ById('pbtargetamountFood').addEventListener('keyup', function(){
			if (isNaN(ById('pbtargetamountFood').value)) ById('pbtargetamountFood').value=0 ;
		}, false);
		ById('pbtargetamountWood').addEventListener('keyup', function(){
			if (isNaN(ById('pbtargetamountWood').value)) ById('pbtargetamountWood').value=0 ;
		}, false);
		ById('pbtargetamountStone').addEventListener('keyup', function(){
			if (isNaN(ById('pbtargetamountStone').value)) ById('pbtargetamountStone').value=0 ;
		}, false);
		ById('pbtargetamountOre').addEventListener('keyup', function(){
			if (isNaN(ById('pbtargetamountOre').value)) ById('pbtargetamountOre').value=0 ;
		}, false);
		ById('pbtargetamountAstone').addEventListener('keyup', function(){
			if (isNaN(ById('pbtargetamountAstone').value)) ById('pbtargetamountAstone').value=0 ;
		}, false);
		ById('pbtargetamountGold').addEventListener('keyup', function(){
			if (isNaN(ById('pbtargetamountGold').value)) ById('pbtargetamountGold').value=0 ;
		}, false);
		ById('pbtradeamountFood').addEventListener('keyup', function(){
			if (isNaN(ById('pbtradeamountFood').value)) ById('pbtradeamountFood').value=0 ;
		}, false);
		ById('pbtradeamountWood').addEventListener('keyup', function(){
			if (isNaN(ById('pbtradeamountWood').value)) ById('pbtradeamountWood').value=0 ;
		}, false);
		ById('pbtradeamountStone').addEventListener('keyup', function(){
			if (isNaN(ById('pbtradeamountStone').value)) ById('pbtradeamountStone').value=0 ;
		}, false);
		ById('pbtradeamountOre').addEventListener('keyup', function(){
			if (isNaN(ById('pbtradeamountOre').value)) ById('pbtradeamountOre').value=0 ;
		}, false);
		ById('pbtradeamountAstone').addEventListener('keyup', function(){
			if (isNaN(ById('pbtradeamountAstone').value)) ById('pbtradeamountAstone').value=0 ;
		}, false);
		ById('pbtradeamountGold').addEventListener('keyup', function(){
			if (isNaN(ById('pbtradeamountGold').value)) ById('pbtradeamountGold').value=0 ;
		}, false);
		ById('pbminwagons').addEventListener('keyup', function(){
			if (isNaN(ById('pbminwagons').value)) ById('pbminwagons').value=100 ;
			Options.minwagons = parseInt(ById('pbminwagons').value);
			saveOptions();
		}, false)

		ById('pbshipFood').addEventListener('click', function(){
			if (ById('pbshipFood').checked==false) {
				ById('pbtargetamountFood').disabled = true;
			}
			else {
				ById('pbtargetamountFood').disabled = false;
			}
		},false);
		ById('pbshipWood').addEventListener('click', function(){
			if (ById('pbshipWood').checked==false) {
				ById('pbtargetamountWood').disabled = true;
			}
			else {
				ById('pbtargetamountWood').disabled = false;
			}
		},false);
		ById('pbshipStone').addEventListener('click', function(){
			if (ById('pbshipStone').checked==false) {
				ById('pbtargetamountStone').disabled = true;
			}
			else {
				ById('pbtargetamountStone').disabled = false;
			}
		},false);
		ById('pbshipOre').addEventListener('click', function(){
			if (ById('pbshipOre').checked==false) {
				ById('pbtargetamountOre').disabled = true;
			}
			else {
				ById('pbtargetamountOre').disabled = false;
			}
		},false);
		ById('pbshipAstone').addEventListener('click', function(){
			if (ById('pbshipAstone').checked==false) {
				ById('pbtargetamountAstone').disabled = true;
			}
			else {
				ById('pbtargetamountAstone').disabled = false;
			}
		},false);
		ById('pbshipGold').addEventListener('click', function(){
			if (ById('pbshipGold').checked==false) {
				ById('pbtargetamountGold').disabled = true;
			}
			else {
				ById('pbtargetamountGold').disabled = false;
			}
		},false);

	},
	checkAutoRoutes: function() {
		var t = Tabs.Transport
		for (var i=t.tradeRoutes.length-1;i>=0;i--) {
			var r = t.tradeRoutes[i];
			if (Cities.byID[r.city] == undefined) {
				//Route loeschen
				t.tradeRoutes.splice(i, 1);
				actionLog(culang.mainTransport,culang.transportDelRoute);
				continue;
			}
			if (r.target_CityId > 0 && Cities.byID[r.target_CityId] == undefined) {
				//Route loeschen
				t.tradeRoutes.splice(i, 1);
				actionLog(culang.mainTransport,culang.transportDelRoute);
				continue;
			}
		}
	},
	
	updateResources2 : function (){
		var t = Tabs.Transport
		t.reapproState.city = t.reacp.city.idx;
		for (var y=0; y< Seed.cities.length;y++) {
			if (t.reacp.city.id==Seed.cities[y][0]) {
				ById('ReappRes_'+y+'_0').value="0";
				ById('ReappRes_'+y+'_0').disabled=true;
			}else {
				ById('ReappRes_'+y+'_0').disabled=false;
				ById('ReappRes_'+y+'_0').value=parseIntNan(t.reapproState['ReappRes_'+y+'_0']);
				ById('ReappRec_'+y+'_0').innerHTML = addCommas ( parseIntNan(Seed.citystats["city" + Seed.cities[y][0]]['gold'][0]) );
			}
			for (var i=1;i<=5;i++) {
				if (t.reacp.city.id==Seed.cities[y][0]) {
					ById('ReappRes_'+y+'_'+i).value="0";
					ById('ReappRes_'+y+'_'+i).disabled=true;
				} else{
					ById('ReappRes_'+y+'_'+i).value= parseIntNan(t.reapproState['ReappRes_'+y+'_'+i]);
					ById('ReappRes_'+y+'_'+i).disabled=false;
				}
				if(i==5)
					ById('ReappRec_'+y+'_'+i).innerHTML = addCommas ( parseIntNan(Seed.resources["city" + Seed.cities[y][0]]['rec'+i][0]) );
				else
					ById('ReappRec_'+y+'_'+i).innerHTML = addCommas ( parseIntNan(Seed.resources["city" + Seed.cities[y][0]]['rec'+i][0]/3600));
			}

		}

	},
	updateResources : function (){
		var t = Tabs.Transport
		var ToCity = null;
		for (var i=1;i<=5;i++)
			if(i==5)
				ById('TransRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + t.tcp.city.id]['rec'+i][0]) );
			else
				ById('TransRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + t.tcp.city.id]['rec'+i][0]/3600) );
		ById('TransGold').innerHTML = addCommas ( parseInt(Seed.citystats["city" + t.tcp.city.id]['gold'][0]) );
		for (ii in Seed.cities)
			if (Seed.cities[ii][2] == document.getElementById ('ptcityX').value && Seed.cities[ii][3] == document.getElementById ('ptcityY').value)
				ToCity = Seed.cities[ii][0];
		for (var i=1;i<=5;i++)
			if (ToCity != null)
				if(i==5)
					ById('HaveRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + ToCity]['rec'+i][0]) );
				else
					ById('HaveRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + ToCity]['rec'+i][0]/3600) );
			else ById('HaveRec'+i).innerHTML = "----";
		if (ToCity != null) ById('HaveGold').innerHTML = addCommas ( parseInt(Seed.citystats["city" + ToCity]['gold'][0]) );
		else  ById('HaveGold').innerHTML =  "----";
		t.updateTroops(t.tcp.city.id);
	},

	updateTroops : function (city){
		var t = Tabs.Transport;
		var fontcolor = 'black';
		t.Food = parseInt(ById('pbtradeamountFood').value);
		t.Wood = parseInt(ById('pbtradeamountWood').value);
		t.Stone = parseInt(ById('pbtradeamountStone').value);
		t.Ore = parseInt(ById('pbtradeamountOre').value);
		t.Gold = parseInt(ById('pbtradeamountGold').value);
		t.Astone = parseInt(ById('pbtradeamountAstone').value*5);
		var unit = ById('TransportTroop').value;
		t.Troops = parseInt(Seed.units['city' + t.tcp.city.id][unit]);
		var untid=unit.substr(3);
		var LoadUnit = getMaxLoad(untid,1);
		var GlobalMaxLoad = t.Troops * LoadUnit;
		t.MaxLoad = parseInt(ById('TroopsToSend').value) * LoadUnit;
		t.TroopsNeeded = (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit;
		t.TroopsNeeded = t.TroopsNeeded.toFixed(0);
		if (t.TroopsNeeded < ((t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit)) t.TroopsNeeded++;
		if (t.TroopsNeeded  > t.Troops) fontcolor = 'red';
		if (t.Troops > 0 ) ById('TroopAmount').innerHTML = '<FONT color='+fontcolor+'>' + addCommas(t.Troops) + '</font>';
		else ById('TroopAmount').innerHTML = 0;
		if (GlobalMaxLoad > 0) ById('CarryAmount').innerHTML = addCommas(GlobalMaxLoad);
		else  ById('CarryAmount').innerHTML = 0;
		ById('Calc').innerHTML = ''+culang.mainRessources+': ' +  addCommas(t.Food + t.Wood + t.Stone + t.Ore + t.Gold  + t.Astone) + ' / ' + addCommas(t.MaxLoad) + '&nbsp;&nbsp;('+culang.transportAutoNeedTroops+' <FONT color='+fontcolor+'>' + addCommas(t.TroopsNeeded) + '</font> )' ;
	},

	e_tradeRoutes: function(){
		var t = Tabs.Transport;
		clearTimeout(t.timer2);
		var now = new Date();
		if (t.traderState.running == true)    {
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			var last = Options.lasttransport;
			if ( now > (parseInt(last) + (Options.transportinterval*60))){
				t.checkdoTrades();
			}
		}
		t.timer2 = setTimeout(function(){ t.e_tradeRoutes();}, Options.transportinterval*60*1000);

	},

	delTradeRoutes: function() {
		var t = Tabs.Transport;
		t.tradeRoutes= [];
	},

	checkcoords : function (obj){
		var t = Tabs.Transport;
		if(obj.id == 'pbok'){
			t.check = true;
			t.addTradeRoute();
		}
		return;
	},

	addTradeRoute: function () {
		var valid = true;
		var t = Tabs.Transport;
		var city = t.tcp.city.id;
		if (ById('ptcityX').value==0 && ById('ptcityY').value ==0 && !t.check)
		{
			return;
		}
		var ship_Food = ById('pbshipFood').checked;
		var ship_Wood = ById('pbshipWood').checked;
		var ship_Stone = ById('pbshipStone').checked;
		var ship_Ore = ById('pbshipOre').checked;
		var ship_Astone = ById('pbshipAstone').checked;
		var ship_Gold = ById('pbshipGold').checked;
		var target_Food = ById('pbtargetamountFood').value;
		var target_Wood = ById('pbtargetamountWood').value;
		var target_Stone = ById('pbtargetamountStone').value;
		var target_Ore = ById('pbtargetamountOre').value;
		var target_Astone = ById('pbtargetamountAstone').value;
		var target_Gold = ById('pbtargetamountGold').value;
		var trade_Food = ById('pbtradeamountFood').value;
		var trade_Wood = ById('pbtradeamountWood').value;
		var trade_Stone = ById('pbtradeamountStone').value;
		var trade_Ore = ById('pbtradeamountOre').value;
		var trade_Astone = ById('pbtradeamountAstone').value;
		var trade_Gold = ById('pbtradeamountGold').value;
		var target_x = ById('ptcityX').value;
		var target_y = ById('ptcityY').value;
		var target_CityId = 0;
		for (var ii in Seed.cities)
			if (Seed.cities[ii][2] == target_x && Seed.cities[ii][3] == target_y)
				target_CityId = Seed.cities[ii][0];
		var TroopType = ById('TransportTroop').value;
		var route_state = true;

		if (valid == true) {
			var lTR = t.tradeRoutes;
			lTR.push({
				city:						city,
				ship_Food:			ship_Food,
				target_Food:		target_Food,
				trade_Food: 		trade_Food,
				ship_Wood:			ship_Wood,
				target_Wood:		target_Wood,
				trade_Wood: 		trade_Wood,
				ship_Stone:			ship_Stone,
				target_Stone:		target_Stone,
				trade_Stone: 		trade_Stone,
				ship_Ore:				ship_Ore,
				target_Ore:			target_Ore,
				trade_Ore:	 		trade_Ore,
				ship_Astone:	  ship_Astone,
				target_Astone:	target_Astone,
				trade_Astone:	 	trade_Astone,
				ship_Gold:			ship_Gold,
				target_Gold:		target_Gold,
				trade_Gold: 		trade_Gold,
				target_x: 			target_x,
				target_y: 			target_y,
				target_CityId:	target_CityId,
				TroopType:      TroopType,
				route_state: 		"true"
			});
		}
		ById('pbTraderDivDRoute').style.background ='#99FF99';
		setTimeout(function(){ (ById('pbTraderDivDRoute').style.background =''); }, 500);
	},
	showTradeRoutes: function () {
		var t = Tabs.Transport;
		if (t.popTradeRoutes == null) {
			t.popTradeRoutes = new CPopup('pbShowTrade', 0, 0, 750, 500, true, function() {clearTimeout (1000);});
			t.popTradeRoutes.centerMe (mainPop.getMainDiv());
		}
		var m = '<DIV style="max-height:450px; overflow:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pdxTab" id="pbRoutesQueue">';
		t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
		t.popTradeRoutes.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.transportAutoRoutes+'</div>';
		t.paintTradeRoutes();
		t.popTradeRoutes.show(true)	;
	},
	paintTradeRoutes: function(){
		var t = Tabs.Transport;
		var r = t.tradeRoutes;
		var cityname;
		var citynameTo = null;
		var m= '<TABLE id=paintRoutes class=pdxTab>';
		for (var i=0;i<(r.length);i++) {
			citynameTo = null;
			for (var y=0; y< Seed.cities.length;y++) {
				if ( parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
				if (r[i].target_CityId && r[i].target_CityId != 0) {
					r[i].target_x = Cities.byID[r[i].target_CityId].x;
					r[i].target_y = Cities.byID[r[i].target_CityId].y;
				}
				if ( parseInt(Seed.cities[y][2]) == r[i].target_x && parseInt(Seed.cities[y][3]) == r[i].target_y) var citynameTo = Seed.cities[y][1];
			}
			var queueId = i;
			if (citynameTo == null) var TO = r[i].target_x +','+ r[i].target_y;
			else TO = citynameTo;
			if (r[i].route_state) var status = '<FONT color=green>'+culang.transportAutoRoutesActive+'</font>';
			else var status = '<FONT color=red>'+culang.transportAutoRoutesDisabled+'</font>';
			if (r[i].TroopType == undefined) var unit = 'unt9';
			else var unit = r[i].TroopType;
			m += '<TR><TD TD width=12px>&nbsp;&nbsp;</td></tr>';
			m +='<TR><TD width=20px>'+(i+1)+'</td><TD width=175px><u>'+culang.mainFrom+'</u>:&nbsp;&nbsp;'+ cityname +'</TD><TD width=175px><u>'+culang.mainTo+'</u>:&nbsp;&nbsp;'+ TO +'</td><TD width=175px>'+status+'</td>';
			m +='<TD width=60px><A onclick="traceEdit('+queueId+')">'+culang.buttonEdit+'</a></td><TD width=60px><A onclick="traceDelete('+queueId+')"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></a></td></tr>';
			m += '<TR><TD></td><TD>'+culang.mainTroops+':&nbsp;&nbsp;'+uW.unitcost[unit][0]+'</td></tr>';
			if (r[i].ship_Food) m += '<TR><TD></td><TD align=center><img src="'+IMGfood30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Food) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Food)+'</td>';
			if (r[i].ship_Wood) m += '<TR><TD></td><TD align=center><img src="'+IMGwood30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Wood) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Wood)+'</td>';
			if (r[i].ship_Stone) m += '<TR><TD></td><TD align=center><img src="'+IMGstone30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Stone) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Stone)+'</td>';
			if (r[i].ship_Ore) m += '<TR><TD></td><TD align=center><img src="'+IMGiron30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Ore) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Ore)+'</td>';
			if (r[i].ship_Astone) m += '<TR><TD></td><TD align=center><img src="'+IMGastone30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Astone) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Astone)+'</td>';
			if (r[i].ship_Gold) m += '<TR><TD></td><TD align=center><img src="'+IMGgold30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Gold) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Gold)+'</td>';
		}
		m +='</table>';
		ById('pbRoutesQueue').innerHTML= m;
		uW.traceEdit = t.editQueueElement;
		uW.traceDelete = t.cancelQueueElement;
	},

	cancelQueueElement: function(queueId){
		var t = Tabs.Transport;
		var queueId = parseInt(queueId);
		t.tradeRoutes.splice(queueId, 1);
		t.showTradeRoutes();
	},

	editQueueElement: function(queueId){
		var t = Tabs.Transport;
		var r = t.tradeRoutes;
		var queueId = parseInt(queueId);
		var cityname;
		var citynameTo = null;
		var Types = ['food','wood','stone','iron','aetherstone','gold'];
		for (var y=0; y< Seed.cities.length;y++) {
			if ( parseInt(Seed.cities[y][0]) == r[queueId].city) var cityname = Seed.cities[y][1];
			if ( parseInt(Seed.cities[y][2]) == r[queueId].target_x && parseInt(Seed.cities[y][3]) == r[queueId].target_y) var citynameTo = Seed.cities[y][1];
		}
		if (citynameTo == null) var TO = r[queueId].target_x +','+ r[queueId].target_y;
		else TO = citynameTo;
		var n = '<TABLE id=editRoutes class=pdxTab>';
		n +='<TD><u>'+culang.mainFrom+'</u>:&nbsp;'+ cityname +'</td><TD><u>'+culang.mainTo+'</u>:&nbsp;'+ TO +'</td>';
		n +='<TD><INPUT id=TradeStatus type=checkbox>&nbsp;'+culang.transportAutoActivateRoute+'</td>';
		n += '<TD width=150px><b>'+culang.mainTroops+'</b>: <SELECT id="pbbTransportTroop">';
		for (y in uW.unitcost) n+='<option value="'+y+'">'+uW.unitcost[y][0]+'</option>';
		n+='</select></td></table><BR><TABLE  id=editRoutes class=pdxTab>';
		for (var i=0;i<Types.length;i++){
			var icon = Types[i];
			n += '<TR><TD width=50px align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/'+icon+'_30.png"></td>';
			n += '<TD width=50px align=center><INPUT id=pbbship'+Types[i]+' type=checkbox></td>';
			n += '<TD width=125px>'+culang.transportSupplyKeep+' <INPUT id=pbbtargetamount'+Types[i]+' type=text size=11 maxlength=12 value="0"></td>';
			n += '<TD width=125px>'+culang.mainTransport+': <INPUT id=pbbtradeamount'+Types[i]+' type=text size=11 maxlength=12 value="0"\></td></tr>';
		}
		n+='</table><BR><TABLE id=editRoutes class=pdxTab><TR><TD><a id="Cancel"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a></td>';
		n+='<TD><a class="button20" id="Save"><span>'+culang.buttonSave+'</span></a></td></tr>';
		n +='</table>';

		ById('pbRoutesQueue').innerHTML= n;
		ById('TradeStatus').checked = r[queueId].route_state;
		if (r[queueId].TroopType == undefined) var unit = 'unt9';
		else var unit = r[queueId].TroopType;
		ById('pbbTransportTroop').value = unit;
		ById('pbbshipfood').checked = r[queueId].ship_Food;
		ById('pbbshipwood').checked = r[queueId].ship_Wood;
		ById('pbbshipstone').checked = r[queueId].ship_Stone;
		ById('pbbshipiron').checked = r[queueId].ship_Ore;
		ById('pbbshipaetherstone').checked = r[queueId].ship_Astone;
		ById('pbbshipgold').checked = r[queueId].ship_Gold;
		ById('pbbtargetamountfood').value = r[queueId].target_Food;
		ById('pbbtargetamountwood').value = r[queueId].target_Wood;
		ById('pbbtargetamountstone').value = r[queueId].target_Stone;
		ById('pbbtargetamountiron').value = r[queueId].target_Ore;
		ById('pbbtargetamountaetherstone').value = r[queueId].target_Astone;
		ById('pbbtargetamountgold').value = r[queueId].target_Gold;
		ById('pbbtradeamountfood').value = r[queueId].trade_Food;
		ById('pbbtradeamountwood').value = r[queueId].trade_Wood;
		ById('pbbtradeamountstone').value = r[queueId].trade_Stone;
		ById('pbbtradeamountiron').value = r[queueId].trade_Ore;
		ById('pbbtradeamountaetherstone').value = r[queueId].trade_Astone;
		ById('pbbtradeamountgold').value = r[queueId].trade_Gold;
		ById('Cancel').addEventListener('click', function(){t.showTradeRoutes();}, false);
		ById('Save').addEventListener('click', function(){
			r[queueId].route_state = ById('TradeStatus').checked;
			r[queueId].TroopType = ById('pbbTransportTroop').value;
			r[queueId].ship_Food = ById('pbbshipfood').checked;
			r[queueId].ship_Wood = ById('pbbshipwood').checked;
			r[queueId].ship_Stone = ById('pbbshipstone').checked;
			r[queueId].ship_Ore = ById('pbbshipiron').checked;
			r[queueId].ship_Astone = ById('pbbshipaetherstone').checked;
			r[queueId].ship_Gold = ById('pbbshipgold').checked;
			r[queueId].target_Food = ById('pbbtargetamountfood').value;
			r[queueId].target_Wood = ById('pbbtargetamountwood').value;
			r[queueId].target_Stone = ById('pbbtargetamountstone').value;
			r[queueId].target_Ore = ById('pbbtargetamountiron').value;
			r[queueId].target_Astone = ById('pbbtargetamountaetherstone').value;
			r[queueId].target_Gold = ById('pbbtargetamountgold').value;
			r[queueId].trade_Food = ById('pbbtradeamountfood').value;
			r[queueId].trade_Wood = ById('pbbtradeamountwood').value;
			r[queueId].trade_Stone = ById('pbbtradeamountstone').value;
			r[queueId].trade_Ore = ById('pbbtradeamountiron').value;
			r[queueId].trade_Astone = ById('pbbtradeamountaetherstone').value;
			r[queueId].trade_Gold = ById('pbbtradeamountgold').value;
			t.showTradeRoutes();
		}, false);
	},

	saveTradeRoutes: function(){
		var t = Tabs.Transport;
		var serverID = getServerId();
		GM_setValue('tradeRoutes_' + serverID, JSON2.stringify(t.tradeRoutes));
	},
	readTradeRoutes: function(){
		var t = Tabs.Transport;
		var serverID = getServerId();
		s = GM_getValue('tradeRoutes_' + serverID);
		if (s != null) {
			route = JSON2.parse(s);
			for (k in route)
				t.tradeRoutes[k] = route[k];
		}
	},
	saveTraderState: function(){
		var t = Tabs.Transport;
		var serverID = getServerId();
		GM_setValue('traderState_' + serverID, JSON2.stringify(t.traderState));
	},
	readTraderState: function(){
		var t = Tabs.Transport;
		var serverID = getServerId();
		s = GM_getValue('traderState_' + serverID);
		if (s != null) {
			state = JSON2.parse(s);
			for (k in state)
				t.traderState[k] = state[k];
		}
	},
	toggleTraderState: function(obj){
		var t = Tabs.Transport;
		obj = ById('pbTraderState');
		if (t.traderState.running == true) {
			t.traderState.running = false;
			if (obj)  obj.value = culang.mainTransport+" = "+culang.buttonOFF;
			clearTimeout(t.checkdotradetimeout);
			clearTimeout(t.timer2);
			t.count = 0;
			Options.lasttransport = 0;
			saveOptions();
		}
		else {
			t.traderState.running = true;
			if (obj) obj.value = culang.mainTransport+" = "+culang.buttonON;
			t.e_tradeRoutes();
		}
	},

	checkdoTrades: function(){
		var t = Tabs.Transport;
		if(t.tradeRoutes.length==0) return;
		t.doTrades(t.count);
		t.count++;
		if(t.count < t.tradeRoutes.length){
			t.checkdotradetimeout = setTimeout(function() { t.checkdoTrades();}, 5000);
		} else {
			var now = new Date().getTime()/1000.0;
			now = now.toFixed(0);
			Options.lasttransport = now;
			saveOptions();
			t.count = 0;
		}
	},

	doTrades: function(count){
		var t = Tabs.Transport;

		if(t.tradeRoutes.length==0) return;
		if(!t.tradeRoutes[count]["route_state"]) return;

		var city = t.tradeRoutes[count]["city"];
		if(!Cities.byID[city]) return;

		if (t.tradeRoutes[count].target_CityId && t.tradeRoutes[count].target_CityId != 0) {
			t.tradeRoutes[count].target_x = Cities.byID[t.tradeRoutes[count].target_CityId].x;
			t.tradeRoutes[count].target_y = Cities.byID[t.tradeRoutes[count].target_CityId].y;
		}
		
		var xcoord = t.tradeRoutes[count]["target_x"];
		var ycoord = t.tradeRoutes[count]["target_y"];
		var cityID = 'city' + city;
		var toCityName = '';
		for (var zz=0; zz< Seed.cities.length;zz++) {
			if (parseInt(Seed.cities[zz][0]) == city) {
				var cityname = Seed.cities[zz][1];
			}
			if (parseInt(Seed.cities[zz][2]) == xcoord && parseInt(Seed.cities[zz][3]) == ycoord) {
				toCityName = ' ('+Seed.cities[zz][1]+')';
			}
		}
		var RInfo = getRallypointInfo(city);
		if(RInfo.usedSlots >= RInfo.maxMarches){
			actionLog(""+culang.mainTransport+"",""+culang.transportSupplyLogTransport+" "+cityname+" "+culang.transportSupplyLogTransport2+" " + xcoord + "," + ycoord + " <font color=red>"+culang.transportSupplyLogFullRP+"</font>");
			return;
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.gold =0;
		params.r1 =0;
		params.r2 =0;
		params.r3 =0;
		params.r4 =0 ;
		params.r5 =0 ;
		params.kid = 0;

		var carry_amount= 0;
		var wagons_needed=0;
		var citymax = 0;

		var trade_Food = t.tradeRoutes[count]["trade_Food"];
		var trade_Wood = t.tradeRoutes[count]["trade_Wood"];
		var trade_Stone = t.tradeRoutes[count]["trade_Stone"];
		var trade_Ore = t.tradeRoutes[count]["trade_Ore"];
		var trade_Astone = t.tradeRoutes[count]["trade_Astone"];
		var trade_Gold = t.tradeRoutes[count]["trade_Gold"];
		var target_Food = t.tradeRoutes[count]["target_Food"];
		var target_Wood = t.tradeRoutes[count]["target_Wood"];
		var target_Stone = t.tradeRoutes[count]["target_Stone"];
		var target_Ore = t.tradeRoutes[count]["target_Ore"];
		var target_Astone = t.tradeRoutes[count]["target_Astone"];
		var target_Gold = t.tradeRoutes[count]["target_Gold"];
		var ship_Food = t.tradeRoutes[count]["ship_Food"];
		var ship_Wood = t.tradeRoutes[count]["ship_Wood"];
		var ship_Stone = t.tradeRoutes[count]["ship_Stone"];
		var ship_Ore = t.tradeRoutes[count]["ship_Ore"];
		var ship_Astone = t.tradeRoutes[count]["ship_Astone"];
		var ship_Gold = t.tradeRoutes[count]["ship_Gold"];
		var citymax_Food = parseIntNan(Seed.resources[cityID]['rec1'][0] / 3600);
		var citymax_Wood = parseIntNan(Seed.resources[cityID]['rec2'][0] / 3600);
		var citymax_Stone = parseIntNan(Seed.resources[cityID]['rec3'][0] / 3600);
		var citymax_Ore = parseIntNan(Seed.resources[cityID]['rec4'][0] / 3600);
		var citymax_Astone = parseIntNan(Seed.resources[cityID]['rec5'][0]);
		var citymax_Gold = parseIntNan(Seed.citystats[cityID]['gold']);
		var carry_Food = parseIntNan(citymax_Food - target_Food);
		var carry_Wood = parseIntNan(citymax_Wood - target_Wood);
		var carry_Stone = parseIntNan(citymax_Stone - target_Stone);
		var carry_Ore = parseIntNan(citymax_Ore - target_Ore);
		var carry_Astone = parseIntNan(citymax_Astone - target_Astone);
		var carry_Gold = 0;
		if (carry_Food < 0 || ship_Food==false) carry_Food = 0;
		if (carry_Wood < 0 || ship_Wood==false) carry_Wood = 0;
		if (carry_Stone < 0 || ship_Stone==false) carry_Stone = 0;
		if (carry_Ore < 0 || ship_Ore==false) carry_Ore = 0;
		if (carry_Astone < 0 || ship_Astone==false) carry_Astone = 0;
		if (trade_Food > 0 && (carry_Food > trade_Food)) carry_Food = parseIntNan(trade_Food);
		if (trade_Wood > 0 && (carry_Wood > trade_Wood)) carry_Wood = parseIntNan(trade_Wood);
		if (trade_Stone > 0 && (carry_Stone > trade_Stone)) carry_Stone = parseIntNan(trade_Stone);
		if (trade_Ore > 0 && (carry_Ore > trade_Ore)) carry_Ore = parseIntNan(trade_Ore);
		if (trade_Astone > 0 && (carry_Astone > trade_Astone)) carry_Astone = parseIntNan(trade_Astone);
		carry_Astone *= 5;
		if (t.tradeRoutes[count]['TroopType'] == undefined) var wagons = parseInt(Seed.units[cityID]['unt'+ 9]);
		else var wagons =  parseInt(Seed.units[cityID][t.tradeRoutes[count]['TroopType']]);
		if (parseInt(wagons) > RInfo.maxMarchSize){ wagons = RInfo.maxMarchSize; }
		if (t.tradeRoutes[count]['TroopType'] == undefined) var unit = 'unt9';
		else var unit = t.tradeRoutes[count]['TroopType'];
		var Troops = parseInt(Seed.units[cityID][unit]);
		if(parseInt(Troops)>parseInt(wagons)) Troops = wagons;
		var untid = unit.substr(3);
		var maxloadperwagon = getMaxLoad(untid,1);
		var maxload = (maxloadperwagon * Troops);
		if(wagons <= 0) {return; }
		var shift_Food = parseIntNan(maxload / 9);
		var shift_Wood = parseIntNan(maxload / 9);
		var shift_Stone = parseIntNan(maxload / 9);
		var shift_Ore = parseIntNan(maxload / 9);
		var shift_Astone = parseIntNan(maxload / 9 * 5);
		if ((maxload - carry_Food - carry_Wood - carry_Stone - carry_Ore - carry_Astone) < 0){
			var shift_num=0;
			var shift_spare=0;
			if (carry_Food < shift_Food) {
				shift_spare += (shift_Food - carry_Food);
				shift_Food = carry_Food;
			}
			if (carry_Wood < shift_Wood) {
				shift_spare += (shift_Wood - carry_Wood);
				shift_Wood = carry_Wood;
			}
			if (carry_Stone < shift_Stone) {
				shift_spare += (shift_Stone - carry_Stone);
				shift_Stone = carry_Stone;
			}
			if (carry_Ore < shift_Ore) {
				shift_spare += (shift_Ore - carry_Ore);
				shift_Ore = carry_Ore;
			}
			if (carry_Astone < shift_Astone) {
				shift_spare += (shift_Astone - carry_Astone);
				shift_Astone = carry_Astone;
			}

			while (shift_spare >1) {
				if (carry_Food < (shift_Food + shift_spare)){
					shift_spare = shift_spare - carry_Food;;
					shift_Food = carry_Food;
				}
				else{
					shift_Food = (shift_Food + shift_spare);
					shift_spare = shift_spare- shift_spare;
				}
				if (carry_Wood < (shift_Wood + shift_spare)){
					shift_spare = shift_spare - carry_Wood;;
					shift_Wood = carry_Wood;
				}
				else{
					shift_Wood = shift_Wood + shift_spare;
					shift_spare = shift_spare- shift_spare;
				}
				if (carry_Stone < (shift_Stone + shift_spare)){
					shift_spare = shift_spare - carry_Stone;
					shift_Stone = carry_Stone;
				}
				else{
					shift_Stone = shift_Stone + shift_spare;
					shift_spare = shift_spare- shift_spare;
				}
				if (carry_Ore < (shift_Ore + shift_spare)){
					shift_spare = shift_spare - carry_Ore;
					shift_Ore = carry_Ore;
				}
				else{
					shift_Ore = shift_Ore + shift_spare;
					shift_spare = shift_spare- shift_spare;
				}
				if (carry_Astone < (shift_Astone + shift_spare)){
					shift_spare = shift_spare - carry_Astone;
					shift_Astone = carry_Astone;
				}
				else{
					shift_Astone = shift_Astone + shift_spare;
					shift_spare = shift_spare- shift_spare;
				}
			}

			carry_Food = shift_Food;
			carry_Wood = shift_Wood;
			carry_Stone = shift_Stone;
			carry_Ore = shift_Ore;
			carry_Astone = shift_Astone;
		}

		if (maxload > (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone) && ship_Gold==true) {
			if ((maxload-(carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone)) > (citymax_Gold - target_Gold)){
				carry_Gold = (citymax_Gold - target_Gold);
				if (carry_Gold < 0 ) carry_Gold = 0;
			}
			else carry_Gold = (maxload-(carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone));
			if (trade_Gold > 0 && (carry_Gold > trade_Gold)) carry_Gold = parseInt(trade_Gold);
		}

		wagons_needed = ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon);
		wagons_needed = wagons_needed.toFixed(0);
		if (wagons_needed < ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon)) wagons_needed++;
		if ( wagons_needed < Options.minwagons ) { return; }

		params.cid= city;
		params.type = "1";
		params.xcoord = xcoord;
		params.ycoord = ycoord;
		params.r1 = carry_Food;
		params.r2 = carry_Wood;
		params.r3 = carry_Stone;
		params.r4 = carry_Ore;
		params.r5 = parseInt(carry_Astone/5);
		params.gold = carry_Gold;

		switch (unit){
			case 'unt1': params.u1 = wagons_needed;break;
			case 'unt2': params.u2 = wagons_needed;break;
			case 'unt3': params.u3 = wagons_needed;break;
			case 'unt4': params.u4 = wagons_needed;break;
			case 'unt5': params.u5 = wagons_needed;break;
			case 'unt6': params.u6 = wagons_needed;break;
			case 'unt7': params.u7 = wagons_needed;break;
			case 'unt8': params.u8 = wagons_needed;break;
			case 'unt9': params.u9 = wagons_needed;break;
			case 'unt10': params.u10 = wagons_needed;break;
			case 'unt11': params.u11 = wagons_needed;break;
			case 'unt12': params.u12 = wagons_needed;break;
			case 'unt13': params.u13 = wagons_needed;break;
			case 'unt14': params.u14 = wagons_needed;break;
			case 'unt15': params.u15 = wagons_needed;break;
		}
		if ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) > 0) {

			new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (transport) {
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.ok) {
						var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
						var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
						var ut = uW.unixtime();
						var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
						for(i = 0; i <= unitsarr.length; i++){
							if(params["u"+i]){
								unitsarr[i] = params["u"+i];
							}
						}
						var resources=new Array();
						resources[0] = params.gold;
						for(i=1; i<=4; i++){
							resources[i] = params["r"+i];
						}
						var currentcityid = params.cid;
						uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
								 
						if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
						actionLog(""+culang.mainTransport+"",""+culang.transportAutoLog+" " + cityname + " "+culang.transportAutoLog2+" " + xcoord + ',' + ycoord + toCityName + "  -> "+ uW.unitcost[unit][0] +": " + wagons_needed);
					} else {
						actionLog(""+culang.mainTransport+"",""+culang.transportAutoLog+" " + cityname + " "+culang.transportAutoLog2+" " + xcoord + ',' + ycoord + toCityName + "<br><font color=red>" + uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)) + "</font>");
					}
				},
				onFailure: function (transport) {
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.user_action) {
						actionLog(""+culang.mainTransport+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
						new CdialogCancelContinue('<SPAN class=boldRed>'+culang.transportCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);
					}else{
						actionLog(""+culang.mainTransport+"",""+culang.transportAutoLog+" " + cityname + " "+culang.transportAutoLog2+" " + xcoord + ',' + ycoord + toCityName + "<br><font color=red>" + uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)) + "</font>");
					}
				}

			});
		}
	},

	ManualTransport: function(){
		var t = Tabs.Transport;
		if (document.getElementById ('ptcityX').value == "" || document.getElementById ('ptcityY').value == "") return;
		if ( t.TroopsNeeded > t.Troops) return;

		var params = uW.Object.clone(uW.g_ajaxparams);
		var unitType = ById('TransportTroop').value;
		var untid=unitType.substr(3);
		var LoadUnit = getMaxLoad(untid,1);
		var MaxLoad =  parseInt(Seed.units['city' + t.tcp.city.id][unitType]) * LoadUnit;
		document.getElementById ('errorSpace').innerHTML = '';

		params.kid = 0;
		params.cid=  t.tcp.city.id;
		params.type = "1";
		params.xcoord = parseInt(document.getElementById ('ptcityX').value);
		params.ycoord = parseInt(document.getElementById ('ptcityY').value);
		params.r1 = parseInt(document.getElementById ('pbtradeamountFood').value);
		params.r2 = parseInt(document.getElementById ('pbtradeamountWood').value);
		params.r3 = parseInt(document.getElementById ('pbtradeamountStone').value);
		params.r4 = parseInt(document.getElementById ('pbtradeamountOre').value);
		params.r5 = parseInt(document.getElementById ('pbtradeamountAstone').value);
		params.gold = parseInt(document.getElementById ('pbtradeamountGold').value);

		switch (unitType){
			case 'unt1': params.u1 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt2': params.u2 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt3': params.u3 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt4': params.u4 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt5': params.u5 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt6': params.u6 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt7': params.u7 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt8': params.u8 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt9': params.u9 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt10': params.u10 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt11': params.u11 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt12': params.u12 = parseInt(document.getElementById ('TroopsToSend').value);break;
			case 'unt13': params.u13 = parseInt(document.getElementById ('TroopsToSend').value);break;		
			case 'unt14': params.u14 = parseInt(document.getElementById ('TroopsToSend').value);break;		
			case 'unt15': params.u15 = parseInt(document.getElementById ('TroopsToSend').value);break;	
		}

		if ((params.r1 + params.r2 + params.r3 + params.r4 + params.r5 + params.gold) > 0) {
			new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (transport) {
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.ok) {
						var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
						var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
						var ut = uW.unixtime();
						var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
						for(i = 0; i <= unitsarr.length; i++){
							if(params["u"+i]){
								unitsarr[i] = params["u"+i];
							}
						}
						var resources=new Array();
						resources[0] = params.gold;
						for(i=1; i<=4; i++){
							resources[i] = params["r"+i];
						}
						var currentcityid = params.cid;
						uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
								 
						if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
						document.getElementById ('errorSpace').innerHTML = ''+culang.transportSend+' ' + addCommas(params.r1+params.r2+params.r3+params.r4+params.r5+params.gold) + ' '+culang.transportSend2+' ' + addCommas(parseInt(document.getElementById ('TroopsToSend').value)) + ' ' + uW.unitcost[unitType][0];
						document.getElementById ('pbtradeamountFood').value = 0;
						document.getElementById ('pbtradeamountWood').value = 0;
						document.getElementById ('pbtradeamountStone').value = 0;
						document.getElementById ('pbtradeamountOre').value = 0;
						document.getElementById ('pbtradeamountAstone').value = 0;
						document.getElementById ('pbtradeamountGold').value = 0;
						document.getElementById ('TroopsToSend').value = 0;
					} else {
						var errorcode =  'err_' + rslt.error_code;
						if (rlst.msg == undefined)document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>'+culang.mainError+': ' + uW.g_js_strings.errorcode[errorcode] +'</font>';
						else document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>'+culang.mainError+': ' + rslt.msg +'</font>';
					}
				},
				onFailure: function () {}
			});
		}
	},

	onUnload: function(){
		var t = Tabs.Transport;
		if (!ResetAll) t.saveTradeRoutes();
		if (!ResetAll) t.saveTraderState();
		if (!ResetAll) t.saveReapproState();
	},
	showManuel : function() {
		var t = Tabs.Transport
		var rownum = 0;

		var ModelCity = {};

		function _row (name, row, noTotal){
			if (rownum++ % 2)
				style = '';
			else
				style = ' style = "background: #e8e8e8"';
			var tot = 0;
			var m = [];
			m.push ('<TR style="background: #fff" align=right');
			m.push (style);
			m.push ('><TD');
			m.push (style);
			m.push ('><B>');
			m.push (name);
			m.push ('</td>');
			if (noTotal){
				m.push ('<TD');
				m.push (style);
				m.push ('>&nbsp;</td>');
			} else {
				for (i=0; i<row.length; i++)
					tot += row[i];
				m.push ('<TD style="background: #ffc">');
				m.push (addCommas(tot));
				m.push ('</td>');
			}
			for (i=0; i<row.length; i++){
				m.push ('<TD');
				m.push (style);
				m.push ('>');
				m.push (addCommas(row[i]));
				m.push ('</td>');
			}
			m.push ('</tr>');
			return m.join('');
		}
		dt = new Date ();
		dt.setTime (Seed.player.datejoinUnixTime * 1000);
		if (t.state == null) {
			m = "<DIV class=pdxStat>"+culang.transportHead+"</div>";
			m +="<div id=ptTranportStatus style='text-align:center;overflow-y:auto; max-height:78px; border-bottom:1px solid #141516;'></div>";
			m += "<TABLE width=100% class=pdxTab border=0>\
       <tr align=center><td colspan=2></td></tr>\
       <tr align=center valign=top><td colspan=1 width=50%><b><u>"+culang.mainCastle+"</b></u><br><span id=srcptspeedcity></span></td>\
       <td colspan=1 width=50%  rowspan=2><b><u>"+culang.mainTarget+"</b></u><br><span id=desptspeedcity></span><br>\
       "+culang.transportOrTargetCoord+" <br>X: <input type=text size=4 id=typetrpx value=0>&nbsp;Y: <input type=text size=4 id=typetrpy value=0><br><a href='javascript:void(0);' id='chargelistelieux'>"+culang.mainPlayer+"</a>: <select id='KslisteFavori'></select><br><br><INPUT id='ptttButTransport' type=submit value='"+culang.transportButton+"' style='font-weight:bold'>\
       </td></tr>\
       <tr align=center><td colspan=1><b>"+culang.mainTroops+":</b> <select id=typetrp><option selected value='1'>"+culang.shrsupply+"</option><option selected value='9'>"+culang.shrsupplywagon+"</option><option value='7'>"+culang.shrcavalry+"</option><option value='8'>"+culang.shrheavycavalry+"</option></select>\
       <br><b>"+culang.mainAmount+":</b> <input type=text size=6 value='1000' id='Choixnbwagon'><input type=button id='trswagmax' value='"+culang.buttonMax+"'\><br>\
       <br><b>"+culang.mainRessources+":</b> <input type=radio id='ChoixRess0' name='ChoixRess' value='gold' style='visibility:hidden'><img src='"+IMGgold30+"' onclick=document.getElementById('ChoixRess0').checked=true;Ksestimeres(); height=20 title='"+culang.transportGoldNote+"'>\
       <input type=radio id='ChoixRess1' name='ChoixRess' value='rec1' style='visibility:hidden'><img src='"+IMGfood30+"' onclick=document.getElementById('ChoixRess1').checked=true;Ksestimeres(); height=20 title='"+culang.transportFoodNote+"'>\
       <input type=radio id='ChoixRess2' name='ChoixRess' value='rec2' style='visibility:hidden'><img src='"+IMGwood30+"' onclick=document.getElementById('ChoixRess2').checked=true;Ksestimeres(); height=20 title='"+culang.transportWoodNote+"'>\
       <input type=radio id='ChoixRess3' name='ChoixRess' value='rec3' style='visibility:hidden'><img src='"+IMGstone30+"' onclick=document.getElementById('ChoixRess3').checked=true;Ksestimeres(); height=20 title='"+culang.transportStoneNote+"'>\
       <input type=radio id='ChoixRess4' name='ChoixRess' value='rec4' style='visibility:hidden'><img src='"+IMGiron30+"' onclick=document.getElementById('ChoixRess4').checked=true;Ksestimeres(); height=20 title='"+culang.transportIronNote+"'>\
       <input type=radio id='ChoixRess5' name='ChoixRess' value='rec5' style='visibility:hidden'><img src='"+IMGastone30+"' onclick=document.getElementById('ChoixRess5').checked=true;Ksestimeres(); height=20 title='"+culang.transportAheterstoneNote+"'>\
       </td></tr>\
       <tr><td colspan=2><b>"+culang.transportAmount+"</b> <span id=KsEstimationR></td></tr>\
       </table><div class='pdxStat'>"+culang.transportStatsHead+"</div><div id='statpourTr'></div>";
			t.TransportDiv.innerHTML = m;
			t.destinationCityx = document.getElementById ('typetrpx');
			t.destinationCityy = document.getElementById ('typetrpy');

			t.destinationCityx.addEventListener ('change', t.estimerRes, false);
			t.destinationCityy.addEventListener ('change', t.estimerRes, false);
			document.getElementById ('ChoixRess0').addEventListener ('click', t.estimerRes, false);
			document.getElementById ('ChoixRess1').addEventListener ('click', t.estimerRes, false);
			document.getElementById ('ChoixRess2').addEventListener ('click', t.estimerRes, false);
			document.getElementById ('ChoixRess3').addEventListener ('click', t.estimerRes, false);
			document.getElementById ('ChoixRess4').addEventListener ('click', t.estimerRes, false);
			document.getElementById ('ChoixRess5').addEventListener ('click', t.estimerRes, false);
			t.listeFavoris = document.getElementById ('KslisteFavori');
			t.estimationRes = document.getElementById ('KsEstimationR');
			t.chargelistelieux = document.getElementById ('chargelistelieux');
			t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
			t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);
			var dcp1 = new CdispCityPicker ('ptspeed1', ById('desptspeedcity'), false, t.clickCityDestinationSelect, 1);
			t.TTbutTransport = document.getElementById ('ptttButTransport');
			t.TTbutTransport.addEventListener ('click', t.clickTransportDo, false);
			t.divTranportStatus = document.getElementById ('ptTranportStatus');
			t.statpourTr = document.getElementById ('statpourTr');
			t.typetrp = document.getElementById ('typetrp');
			t.typetrp.addEventListener ('click', t.estimerRes, false);
			t.trswagmax = document.getElementById ('trswagmax');
			t.trswagmax.addEventListener ('click', t.clickUniteMax, false);
			t.Choixnbwagon  = document.getElementById ('Choixnbwagon');
			t.Choixnbwagon.addEventListener ('keyup', t.verifierWagons, false);
			var dcp0 = new CdispCityPicker ('ptspeed0', ById('srcptspeedcity'), false, t.clickCitySourceSelect, Cities.byID[uW.currentcityid].idx);
			t.state = 1;
		}
		if (t.state == 1) {
			if (document.getElementById ('maparea_map').style.display!="none") {
				t.destinationCityx.value = document.getElementById ('mapXCoor').value;
				t.destinationCityy.value = document.getElementById ('mapYCoor').value;
				t.destinationCityx.style.backgroundColor="#FF9999";
				t.destinationCityy.style.backgroundColor="#FF9999";
				setTimeout(function() {
					t.destinationCityx.style.backgroundColor="#fff";
					t.destinationCityy.style.backgroundColor="#fff";
				}, 3000);

			}
			t.state = 2;
		}
		rows=[];
		rows[0]=[];
		m = "<TABLE class=pdxTabLined cellspacing=0><TR valign=top align=right><TD width=65></td><TD width=88 style='background: #ffc'><B>"+culang.mainHTotal+"</b></td>";
		for(i=0; i<Cities.numCities; i++)
			m += '<TD width=81><B>'+ Cities.cities[i].name.substring(0,10) +'</b></td>';
		for(i=0; i<Cities.numCities; i++) {
			cityID = 'city'+ Cities.cities[i].id;
			rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
		}
		for (r=1; r<6; r++){
			rows[r] = [];
			for(i=0; i<Cities.numCities; i++) {
				cityID = 'city'+ Cities.cities[i].id;
				if (r==5)
					rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
				else
					rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
			}
		}
		m += _row ('<img height=20 src="'+IMGgold30+'">', rows[0]);
		m += _row ('<img height=20 src="'+IMGfood30+'">', rows[1]);
		m += _row ('<img height=20 src="'+IMGwood30+'">', rows[2]);
		m += _row ('<img height=20 src="'+IMGstone30+'">', rows[3]);
		m += _row ('<img height=20 src="'+IMGiron30+'">', rows[4]);
		m += _row ('<img height=20 src="'+IMGastone30+'">', rows[5]);
		m += '<TR><TD><font size=1><BR></td></tr>';
		row = [];
		var totalbouffe = 0;
		var MaxUpkeep = uW.cm.thronestats.boosts.Upkeep.Max;
		var TR = Math.min(uW.cm.ThroneController.effectBonus(79), MaxUpkeep) / 100;
	
		for(i=0; i<Cities.numCities; i++) {
			var rp = getResourceProduction (Cities.cities[i].id);
			var usage = parseIntNan(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
			usage = Math.floor(usage - (usage * TR));
			row[i] = rp[1] - usage;
		}
		m += _row (''+culang.overviewSProduce+'', row, false,  0);
		for(i=0; i<Cities.numCities; i++) {
			if (row[i] >= 0)
				row[i] = '----';
			else {
				var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
				if (timeLeft > 86313600)
					row[i] = '----';
				else {
					if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
						row[i] = '<SPAN class=whiteOnRed>'+ timestrShort(timeLeft) +'</span>';
					else
						row[i] = timestrShort(timeLeft);
				}
			}
		}
		m += _row (''+culang.overviewFoodLeft+'', row, true, 0);
		m += '<TR><TD><font size=1><BR></td></tr>';
		for (r=1; r<14; r++){
			rows[r] = [];
			for(i=0; i<Cities.numCities; i++) {
				cityID = 'city'+ Cities.cities[i].id;
				rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
			}
		}
		m += _row ('<img height=20 title="'+uW.unitcost['unt1'][0]+'" src="'+IMGmiddleSupplyTroop+'">', rows[1]);
		m += _row ('<img height=20 title="'+uW.unitcost['unt7'][0]+'" src="'+IMGmiddleCavalry+'">', rows[7]);
		m += _row ('<img height=20 title="'+uW.unitcost['unt8'][0]+'" src="'+IMGmiddleHeavyCavalry+'">', rows[8]);
		m += _row ('<img height=20 title="'+uW.unitcost['unt9'][0]+'" src="'+IMGmiddleSupplyWagon+'">', rows[9]);
		row = [];
		for(i=0; i<Cities.numCities; i++) {
			var RInfo = getRallypointInfo(Cities.cities[i].id);
			row[i] = '<SPAN><B>'+ RInfo.usedSlots +'/'+ RInfo.maxMarches +'</b></span>';
		}
		m += _row (''+culang.mainSRallyPoint+'', row, true, 0);   m += "</table>";
		t.statpourTr.innerHTML = m;
		t.estimerRes();
		clearTimeout (t.displayTimer);
		t.displayTimer = setTimeout (t.showManuel, 1000);
	},

	SelectFavoris:function() {
		var t = Tabs.Transport;
		if (t.listeFavoris.value!='') {
			var valeur=t.listeFavoris.value;
			var x=valeur.substr(0, valeur.lastIndexOf(','));
			var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
			t.destinationCityx.value = x;
			t.destinationCityy.value = y;
		}
		t.estimerRes();
	},

	chercherFavoris: function() {
		var t = Tabs.Transport;
		var myA = getMyAlliance ();
		if (myA[0]!=0) {
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.perPage = 100;
			params.allianceId = myA[0];
			params.type = 'might';
			params.page = 1;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/getUserLeaderboard.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					if (rslt.ok){
						var z=0;
						var m="";
						for (var i=0; i<rslt.results.length; i++){
							p = rslt.results[i];
							if (p.userId != 0){
								for (var c=0; c<p.cities.length; c++){
									if (Seed.player.name!=p.displayName) {
										m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - "+uW.g_js_strings.commonstr.city+" " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
									}
								}
							}
						}
						t.listeFavoris.innerHTML="<option value=''>-- "+culang.mainSelect+" --</option>"+m;
					}
				},
				onFailure: function (rslt) {
					t.listeFavoris.innerHTML="<option>"+culang.mainError+"</option>";
				},
			});
		} else {
			t.listeFavoris.innerHTML="<option>"+culang.transportNoAlliance+"</option>";
		}
	},
	verifierWagons: function() {
		var t = Tabs.Transport;
		var maxw=parseIntNan(rows[t.typetrp.value][t.sourceCity.idx]);
		var saisw=parseIntNan(t.Choixnbwagon.value);
		if (saisw > maxw) {
			t.Choixnbwagon.value=maxw;
			t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatus+'  '+maxw+' '+culang.transportStatus2+'</font>';
		}
		t.estimerRes();
	},
	estimerRes: function() {
		var t = Tabs.Transport;
		var cityID = 'city'+ t.sourceCity.id,ic=0,resact=0,ic_ty="gold",ic_text=" "+uW.g_js_strings.commonstr.gold;
		if (ById("ChoixRess1").checked) { ic_ty="rec1";ic=1;ic_text=" "+uW.g_js_strings.commonstr.food; }
		if (ById("ChoixRess2").checked) { ic_ty="rec2";ic=2;ic_text=" "+uW.g_js_strings.commonstr.wood; }
		if (ById("ChoixRess3").checked) { ic_ty="rec3";ic=3;ic_text=" "+uW.g_js_strings.commonstr.stone; }
		if (ById("ChoixRess4").checked) { ic_ty="rec4";ic=4;ic_text=" "+uW.g_js_strings.commonstr.ore; }
		if (ById("ChoixRess5").checked) { ic_ty="rec5";ic=5;ic_text=" "+uW.g_js_strings.commonstr.aetherstone; }
		if (ById("ChoixRess0").checked) { ic_ty="gold";ic=0;ic_text=" "+uW.g_js_strings.commonstr.gold; }
		var esti = 0;

		var total_units=t.Choixnbwagon.value;
		var untid=t.typetrp.value;
		var esti = getMaxLoad(untid,total_units);
		if (ic==5) {esti = parseInt(esti / 5);}
		var x1 = parseInt(t.sourceCity.x);
		var x2 = parseInt(t.destinationCityx.value);
		var y1 = parseInt(t.sourceCity.y);
		var y2 = parseInt(t.destinationCityy.value);
		var dist = distance (x1, y1, x2, y2);
		var m = estETA(dist,ById('typetrp').value,t.sourceCity.id,1);
		var a="";
		switch(ic){
			case 0:a=uW.g_js_strings.commonstr.gold;break;
			case 1:a=uW.g_js_strings.commonstr.food;break;
			case 2:a=uW.g_js_strings.commonstr.wood;break;
			case 3:a=uW.g_js_strings.commonstr.stone;break;
			case 4:a=uW.g_js_strings.commonstr.ore;break;
			case 5:a=uW.g_js_strings.commonstr.aetherstone;break;
		}
		t.estimationRes.innerHTML = "<span class='boldRed'>" + addCommas(esti) + " <u>"+a+"</u></span>";
		t.estimationRes.innerHTML += "<br><b>"+culang.transportMarchTime+"</b> <span class='boldRed'>" + m.friendEtaStr + "</span>" ;

		if (ic==5)
			resact = parseIntNan(Seed.resources[cityID][ic_ty][0]);
		else {
			if (ic==0)
				resact = parseIntNan(Seed.citystats[cityID].gold[0]);
			else
				resact = parseIntNan(Seed.resources[cityID][ic_ty][0] / 3600);
		}

		if (resact < esti) {

			var untid=t.typetrp.value;
			var nbparunit = getMaxLoad(untid,1);
			if (ic==5) nbparunit=nbparunit/5;
			var uniteness = Math.floor(resact / nbparunit);
			if (uniteness<1) uniteness=0;
			t.Choixnbwagon.value = uniteness;
			t.TTbutTransport.disabled = false;
			t.estimerRes();
		}
	},
	clickUniteMax: function() {
		var t = Tabs.Transport;
		var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
		var RInfo = getRallypointInfo(t.sourceCity.id);
		if (maxw>RInfo.maxMarchSize) maxw=RInfo.maxMarchSize;
		t.Choixnbwagon.value=maxw;
		t.estimerRes();
	},
	clickTransportDo: function() {
		var t = Tabs.Transport;
		var SourceId = t.sourceCity.id;
		var DestinationId = t.destinationCity.id;
		if (!ById("ChoixRess0").checked && !ById("ChoixRess1").checked && !ById("ChoixRess2").checked && !ById("ChoixRess3").checked && !ById("ChoixRess4").checked && !ById("ChoixRess5").checked) {
			t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusRes+'</font>';
			return;
		}
		if (t.sourceCity.x==t.destinationCityx.value && t.sourceCity.y==t.destinationCityy.value) {
			t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusNotPossible+'</font>';
			return;
		}
		if (parseInt(t.Choixnbwagon.value)=="0") {
			t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusNoTroops+'</font>';
			return;
		}
		var x=t.destinationCityx.value;
		var y=t.destinationCityy.value;
		if (x == 0 && y == 0) {
			t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusCoord00+'</font>';
			return;
		}
		t.TTbutTransport.disabled=true;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.kid = 0;
		params.cid= t.sourceCity.id;
		params.type = "1";
		params.xcoord = x;
		params.ycoord = y;
		params.r1 = 0;
		params.r2 = 0;
		params.r3 = 0;
		params.r4 = 0;
		params.r5 = 0;
		params.gold = 0;
		params.u9 = 0;
		var untid=t.typetrp.value
		var esti = getMaxLoad(untid,t.Choixnbwagon.value);
		if (ById("ChoixRess5").checked) {
			esti = parseInt(esti / 5);
		}
		if (ById("ChoixRess0").checked) { params.gold = esti; }
		if (ById("ChoixRess1").checked) { params.r1 = esti; }
		if (ById("ChoixRess2").checked) { params.r2 = esti; }
		if (ById("ChoixRess3").checked) { params.r3 = esti; }
		if (ById("ChoixRess4").checked) { params.r4 = esti; }
		if (ById("ChoixRess5").checked) { params.r5 = esti; }
		if (t.typetrp.value==1)  params.u1 = t.Choixnbwagon.value;
		if (t.typetrp.value==9)  params.u9 = t.Choixnbwagon.value;
		if (t.typetrp.value==7)  params.u7 = t.Choixnbwagon.value;
		if (t.typetrp.value==8)  params.u8 = t.Choixnbwagon.value;

		t.divTranportStatus.innerHTML = "<i><b>"+culang.transportLoading+"</b></i>";
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var t = Tabs.Transport;
				var rslt = transport;
				if (rslt.ok) {
					var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
          var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
							unitsarr[i] = params["u"+i];
						}
					}
					var resources=new Array();
					resources[0] = params.gold;
					for(i=1; i<=4; i++){
						resources[i] = params["r"+i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
					t.divTranportStatus.innerHTML = "<font size='3px'><i><b>"+culang.transportOK+"</b></i></font>";
					t.TTbutTransport.disabled=false;
				} else {
					t.divTranportStatus.innerHTML ="<font color=red size='3px'><i><b>"+culang.transportMiss+"</b></i></font>";
					if (rslt.msg) {
						t.divTranportStatus.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";
						t.TTbutTransport.disabled=false;
					} else {
						t.divTranportStatus.innerHTML +="<br><i><b>"+culang.transportStartIn2Seconds+"</b></i></font>";
						setTimeout(function() { t.clickTransportDo(); }, 2000);
					}
				}
			},
			onFailure: function (rslt) {
				var t = Tabs.Transport;
				if (rslt.user_action) {
					t.divTranportStatus.innerHTML ="<font color=red size='3px'><i><b>"+culang.movementCaptchaAlert+"</b></i></font>";
				} else {

					t.divTranportStatus.innerHTML ="<font color=red size='3px'><i><b>"+culang.transportMiss+"</b></i></font>";
				}
				t.TTbutTransport.disabled=false;
			}
		});
	},
	clickCitySourceSelect : function (city){
		var t = Tabs.Transport;
		t.sourceCity = city;
		t.TTbutTransport.disabled=false;
		var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
		var saisw=parseInt(t.Choixnbwagon.value);
		if (saisw > maxw)  t.Choixnbwagon.value=maxw;
		t.estimerRes();
	},
	clickCityDestinationSelect : function (city){
		var t = Tabs.Transport;
		t.destinationCity = city;
		t.destinationCityx.value=t.destinationCity.x;
		t.destinationCityy.value=t.destinationCity.y;
		t.TTbutTransport.disabled=false;
		t.estimerRes();
	},

}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Reassign.js">
//	
//	   KOC POWER - TABS REASSING										        
//	


var troops = {
	1: 'SupplyTroops',
	2: 'Militiaman',
	3: 'Scout',
	4: 'Pikeman',
	5: 'Swordsman',
	6: 'Archer',
	7: 'Cavalry',
	8: 'HeavyCavalry',
	9: 'SupplyWagon',
	10: 'Ballista',
	11: 'BatteringRam',
	12: 'Catapult',
	13: 'BloodThom',
	14: 'Executioner',
	15: 'SiegeWall',
	16: 'FlameArcher',
	17: 'Husar',
};
Tabs.Reassign = {
	tabOrder: TabOptions.toReassign,
	tabLabel: culang.tabLabelReassign,
	cont: null,
	displayTimer: null,
	state: null,
	curTabBut: null,
	curTabName: null,
	sourceCity: {},
	destinationCity: {},
	rows: [],
	timer: null,
	reassignState: [],
	lRE: [],
	reassignRoutes: [],
	rallypointlevel: null,
	count: 0,
	check: false,

	show: function () {},
	hide: function () {
		var t = Tabs.Reassign;
		t.state = null;
		clearTimeout(t.displayTimer);
		clearTimeout(t.timer);
	},
	init: function (div) {
		var t = Tabs.Reassign;
		t.cont = div;
		t.reassignState = {
			running: false,
		};
		t.readReassignState();
		t.readReassignRoutes();
		t.e_reassignRoutes();
		window.addEventListener('unload', t.onUnload, false);
		
		t.checkAutoRoutes();
		t.cont = div;
		t.cont.innerHTML = '<TABLE class=pdxTab align=center><TR><TD><INPUT class=ksMSubtab ID=BoReeSubM type=submit value="' + culang.reassignTabLabel + '"></td>\
             <TD><INPUT class=ksMSubtab ID=BoReeSubA type=submit  value="' + culang.reassignAutoTabLabel + '"></td></tr></table>\
         <DIV id="BoReeOutput" style="margin-top:5px; background-color:white;"></div>';
		t.ReassignDiv = ById('BoReeOutput');
		ById('BoReeSubA').addEventListener('click', e_butSubtab, false);
		ById('BoReeSubM').addEventListener('click', e_butSubtab, false);
		changeSubtab(ById('BoReeSubM'));

		function e_butSubtab(evt) {
			changeSubtab(evt.target);
		}

		function changeSubtab(but) {
			if (but == t.curTabBut) return;
			if (t.curTabBut) {
				t.curTabBut.className = 'ksMSubtab';
				t.curTabBut.disabled = false;
			}
			t.curTabBut = but;
			but.className = 'ksMSubtab ksMSubtabSel';
			but.disabled = true;
			t.curTabName = but.id.substr(8);
			t.show2();
		}

	},
	checkAutoRoutes: function() {
		var t = Tabs.Reassign
		for (var i=t.reassignRoutes.length-1;i>=0;i--) {
			var r = t.reassignRoutes[i];
			if (Cities.byID[r.city] == undefined) {
				//Route loeschen
				t.reassignRoutes.splice(i, 1);
				actionLog(culang.tabLabelReassign,culang.reassignDelRoute);
				continue;
			}
			if (Cities.byID[r.city_to] == undefined) {
				//Route loeschen
				t.reassignRoutes.splice(i, 1);
				actionLog(culang.tabLabelReassign,culang.reassignDelRoute);
				continue;
			}
		}
	},
	
	
	show2: function () {
		var t = Tabs.Reassign;
		t.state = null;
		clearTimeout(t.displayTimer);
		if (t.curTabName == 'M') t.showManuel();
		else t.showAuto();
	},

	showAuto: function () {
		var t = Tabs.Reassign;
		clearTimeout(t.timer);
		if (t.state == null) {

			t.state = 1;

			var m = '<DIV id=pbReMainDivF class=pdxStat>' + culang.reassignAutoHead + '</div><TABLE id=pbtraderfunctions width=100% height=0% class=pdxTab><TR align="center">';
			m += '<TD><b>' + culang.mainIntervall + '</b>: <INPUT id=pbreassigninterval type=text size=2 value="' + Options.reassigninterval + '"\> ' + culang.mainMinutes + '</td>';
			m += '<TD><INPUT id=autofilloff type=checkbox unchecked=true\> <span title="' + culang.reassignAutoTroopLockNote + '">' + culang.reassignAutoTroopLock + '</span></td>';
			m += '<TD><INPUT id=pbReassShowRoutes type=submit value="' + culang.mainShowRoutes + '"></td>';
			if (t.reassignState.running == false) {
				m += '<TD><INPUT id=pbReassignState type=submit value="' + culang.mainReassign + '  = ' + culang.buttonOFF + ' "></td>';
			} else {
				m += '<TD><INPUT id=pbReassignState type=submit value="' + culang.mainReassign + '  = ' + culang.buttonON + ' "></td>';
			}

			m += '</tr></table></div>';
			m += '<DIV id=pbReassignDivD class=pdxStat>' + culang.reassignAutoHeadAddRoute + '</div>';

			m += '<TABLE id=pbaddreasignroute width=95% height=0% class=pdxTab><TR align="left">';
			m += '<TD width=20px><b>' + culang.mainCastle + '</b>:</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncity></span></div></td></tr>';

			m += '<TR align="left">';
			m += '<TD width=20px><b>' + culang.mainTarget + '</b>:</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncityTo></span></div></td>';

			m += '</table>';
			m += '<TABLE width=100% class=pdxTab><TR align="center">';
			m += '<TR><TD rowspan="2" width=50><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_1_50.jpg"></td>';
			m += '<TD>' + uW.unitcost['unt1'][0] + '</td>'
			m += '<TD rowspan="2" width=50><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_2_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt2'][0] + '</td>'
			m += '<TD rowspan="2" width=50><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_3_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt3'][0] + '</td>'
			m += '<TD rowspan="2" width=50><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_4_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt4'][0] + '</td></tr>'
			m += '<TR><TD><INPUT id=pbSupplyTroops type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetSupplyTroops disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbMilitiaman type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetMilitiaman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbScout type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetScout disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbPikeman type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetPikeman disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
			m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_5_50.jpg"></td>';
			m += '<TD>' + uW.unitcost['unt5'][0] + '</td>'
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_6_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt6'][0] + '</td>'
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_7_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt7'][0] + '</td>'
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_8_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt8'][0] + '</td></tr>'
			m += '<TR><TD><INPUT id=pbSwordsman type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetSwordsman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbArcher type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetArcher disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbCavalry type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbHeavyCavalry type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetHeavyCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
			m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_9_50.jpg"></td>';
			m += '<TD>' + uW.unitcost['unt9'][0] + '</td>'
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_10_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt10'][0] + '</td>'
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_11_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt11'][0] + '</td>'
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_12_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt12'][0] + '</td>'

			m += '</tr><TR><TD><INPUT id=pbSupplyWagon type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetSupplyWagon disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbBallista type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetBallista disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbBatteringRam type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetBatteringRam disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbCatapult type=checkbox unchecked=true\>';
			m += '<INPUT id=pbtargetCatapult disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
			
			m += '<tr><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt13'][0] + '</td>';
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt14'][0] + '</td>';
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt15'][0] + '</td>';
			m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_16_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt16'][0] + '</td>';
			m += '</tr>';
			m += '<tr><TD><INPUT id=pbBloodThom type=checkbox unchecked=true\><INPUT id=pbtargetBloodThom disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbExecutioner type=checkbox unchecked=true\><INPUT id=pbtargetExecutioner disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbSiegeWall type=checkbox unchecked=true\><INPUT id=pbtargetSiegeWall disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD><INPUT id=pbFlameArcher type=checkbox unchecked=true\><INPUT id=pbtargetFlameArcher disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '</tr>';
			
			m += '<tr><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_17_50.jpg"></td>'
			m += '<TD>' + uW.unitcost['unt17'][0] + '</td>';
			m += '<TD rowspan="2"></td>'
			m += '<TD></td>';
			m += '<TD rowspan="2"></td>'
			m += '<TD></td>';
			m += '<TD rowspan="2"></td>'
			m += '<TD></td>';
			m += '</tr>';
			m += '<tr><TD><INPUT id=pbHusar type=checkbox unchecked=true\><INPUT id=pbtargetHusar disabled=true type=text size=10 maxlength=10 value="0"\></td>';
			m += '<TD></td>';
			m += '<TD></td>';
			m += '<TD></td>';
			m += '</tr></table>';
			m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteReassign type=submit value="' + culang.reassignAutoAddRoute + '"></div>';

			t.ReassignDiv.innerHTML = m;

			t.tcp = new CdispCityPicker('ptreassign', ById('ptassigncity'), true, null, 0);
			t.tcpto = new CdispCityPicker('ptreassignTo', ById('ptassigncityTo'), true);
			for (var k in troops) {
				ById('pbtarget' + troops[k]).value = parseIntNan(Seed.units['city' + t.tcp.city.id]['unt' + k]);
			}

			ById('ptassigncity').addEventListener('click', function () {
				if (ById('autofilloff').checked == false) 
					for (var k in troops)
						ById('pbtarget' + troops[k]).value = parseInt(Seed.units['city' + t.tcp.city.id]['unt' + k]);
			}, false);

			ById('pbReassignState').addEventListener('click', function () {
				t.toggleReassignState(this);
			}, false);
			ById('pbSaveRouteReassign').addEventListener('click', function () {
				t.addReassignRoute();
			}, false);
			ById('pbReassShowRoutes').addEventListener('click', function () {
				t.showReassignRoutes();
			}, false);

			ById('pbreassigninterval').addEventListener('keyup', function () {
				if (isNaN(ById('pbreassigninterval').value)) {
					ById('pbreassigninterval').value = 0;
				}
				Options.reassigninterval = ById('pbreassigninterval').value;
				saveOptions();
			}, false);

			ById('pbtargetSupplyTroops').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetSupplyTroops').value)) ById('pbtargetSupplyTroops').value = 0;
			}, false);
			ById('pbtargetMilitiaman').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetMilitiaman').value)) ById('pbtargetMilitiaman').value = 0;
			}, false);
			ById('pbtargetScout').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetScout').value)) ById('pbtargetScout').value = 0;
			}, false);
			ById('pbtargetPikeman').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetPikeman').value)) ById('pbtargetPikeman').value = 0;
			}, false);
			ById('pbtargetSwordsman').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetSwordsman').value)) ById('pbtargetSwordsman').value = 0;
			}, false);
			ById('pbtargetArcher').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetArcher').value)) ById('pbtargetArcher').value = 0;
			}, false);
			ById('pbtargetCavalry').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetCavalry').value)) ById('pbtargetCavalry').value = 0;
			}, false);
			ById('pbtargetHeavyCavalry').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetHeavyCavalry').value)) ById('pbtargetHeavyCavalry').value = 0;
			}, false);
			ById('pbtargetSupplyWagon').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetSupplyWagon').value)) ById('pbtargetSupplyWagon').value = 0;
			}, false);
			ById('pbtargetBallista').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetBallista').value)) ById('pbtargetBallista').value = 0;
			}, false);
			ById('pbtargetBatteringRam').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetBatteringRam').value)) ById('pbtargetBatteringRam').value = 0;
			}, false);
			ById('pbtargetCatapult').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetCatapult').value)) ById('pbtargetCatapult').value = 0;
			}, false);
			ById('pbtargetBloodThom').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetBloodThom').value)) ById('pbtargetBloodThom').value = 0;
			}, false);
			ById('pbtargetExecutioner').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetExecutioner').value)) ById('pbtargetExecutioner').value = 0;
			}, false);
			ById('pbtargetSiegeWall').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetSiegeWall').value)) ById('pbtargetSiegeWall').value = 0;
			}, false);
			ById('pbtargetFlameArcher').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetFlameArcher').value)) ById('pbtargetFlameArcher').value = 0;
			}, false);
			ById('pbtargetHusar').addEventListener('keyup', function () {
				if (isNaN(ById('pbtargetHusar').value)) ById('pbtargetHusar').value = 0;
			}, false);
			
			ById('pbSupplyTroops').addEventListener('click', function () {
				if (ById('pbSupplyTroops').checked == false) {
					ById('pbtargetSupplyTroops').disabled = true;
				} else {
					ById('pbtargetSupplyTroops').disabled = false;
				}
			}, false);
			ById('pbMilitiaman').addEventListener('click', function () {
				if (ById('pbMilitiaman').checked == false) {
					ById('pbtargetMilitiaman').disabled = true;
				} else {
					ById('pbtargetMilitiaman').disabled = false;
				}
			}, false);
			ById('pbScout').addEventListener('click', function () {
				if (ById('pbScout').checked == false) {
					ById('pbtargetScout').disabled = true;
				} else {
					ById('pbtargetScout').disabled = false;
				}
			}, false);
			ById('pbPikeman').addEventListener('click', function () {
				if (ById('pbPikeman').checked == false) {
					ById('pbtargetPikeman').disabled = true;
				} else {
					ById('pbtargetPikeman').disabled = false;
				}
			}, false);
			ById('pbSwordsman').addEventListener('click', function () {
				if (ById('pbSwordsman').checked == false) {
					ById('pbtargetSwordsman').disabled = true;
				} else {
					ById('pbtargetSwordsman').disabled = false;
				}
			}, false);
			ById('pbArcher').addEventListener('click', function () {
				if (ById('pbArcher').checked == false) {
					ById('pbtargetArcher').disabled = true;
				} else {
					ById('pbtargetArcher').disabled = false;
				}
			}, false);
			ById('pbCavalry').addEventListener('click', function () {
				if (ById('pbCavalry').checked == false) {
					ById('pbtargetCavalry').disabled = true;
				} else {
					ById('pbtargetCavalry').disabled = false;
				}
			}, false);
			ById('pbHeavyCavalry').addEventListener('click', function () {
				if (ById('pbHeavyCavalry').checked == false) {
					ById('pbtargetHeavyCavalry').disabled = true;
				} else {
					ById('pbtargetHeavyCavalry').disabled = false;
				}
			}, false);
			ById('pbSupplyWagon').addEventListener('click', function () {
				if (ById('pbSupplyWagon').checked == false) {
					ById('pbtargetSupplyWagon').disabled = true;
				} else {
					ById('pbtargetSupplyWagon').disabled = false;
				}
			}, false);
			ById('pbBallista').addEventListener('click', function () {
				if (ById('pbBallista').checked == false) {
					ById('pbtargetBallista').disabled = true;
				} else {
					ById('pbtargetBallista').disabled = false;
				}
			}, false);
			ById('pbBatteringRam').addEventListener('click', function () {
				if (ById('pbBatteringRam').checked == false) {
					ById('pbtargetBatteringRam').disabled = true;
				} else {
					ById('pbtargetBatteringRam').disabled = false;
				}
			}, false);
			ById('pbCatapult').addEventListener('click', function () {
				if (ById('pbCatapult').checked == false) {
					ById('pbtargetCatapult').disabled = true;
				} else {
					ById('pbtargetCatapult').disabled = false;
				}
			}, false);
			ById('pbBloodThom').addEventListener('click', function () {
				if (ById('pbBloodThom').checked == false) {
					ById('pbtargetBloodThom').disabled = true;
				} else {
					ById('pbtargetBloodThom').disabled = false;
				}
			}, false);
			ById('pbExecutioner').addEventListener('click', function () {
				if (ById('pbExecutioner').checked == false) {
					ById('pbtargetExecutioner').disabled = true;
				} else {
					ById('pbtargetExecutioner').disabled = false;
				}
			}, false);
			ById('pbSiegeWall').addEventListener('click', function () {
				if (ById('pbSiegeWall').checked == false) {
					ById('pbtargetSiegeWall').disabled = true;
				} else {
					ById('pbtargetSiegeWall').disabled = false;
				}
			}, false);
			ById('pbFlameArcher').addEventListener('click', function () {
				if (ById('pbFlameArcher').checked == false) {
					ById('pbtargetFlameArcher').disabled = true;
				} else {
					ById('pbtargetFlameArcher').disabled = false;
				}
			}, false);
			ById('pbHusar').addEventListener('click', function () {
				if (ById('pbHusar').checked == false) {
					ById('pbtargetHusar').disabled = true;
				} else {
					ById('pbtargetHusar').disabled = false;
				}
			}, false);
		} else {


		}
		t.timer = setTimeout(t.showAuto, 3000);
	},
	getRallypoint: function (cityId) {
		var t = Tabs.Reassign;
		for (var o in Seed.buildings[cityId]) {
			var buildingType = parseInt(Seed.buildings[cityId][o][0]);
			var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
			if (buildingType == 12) {
				t.rallypointlevel = parseInt(buildingLevel);
				if (uW.cm.PrestigeModel.isPrestige(cityId)) {
					var a = uW.cm.PrestigeModel.getPrestigeLevel(cityId);
					if (a > 0) {
						var mm = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
							k = uW.JSON.parse(mm),
							o = k.values[a - 1][2],
							ii = parseFloat(o);
						t.rallypointlevel = t.rallypointlevel + ii;
					}
				}
			}
		}
	},

	e_reassignRoutes: function () {
		var t = Tabs.Reassign;
		var now = new Date();
		if (t.reassignState.running == true) {
			var now = new Date().getTime() / 1000.0;
			now = now.toFixed(0);
			var last = Options.lastreassign;
			if (now > (parseInt(last) + (Options.reassigninterval * 60))) {
				t.checkdoReassign();
			}
		}
		setTimeout(function () {
			t.e_reassignRoutes();
		}, Options.reassigninterval * 1000);

	},

	delReassignRoutes: function () {

		var t = Tabs.Reassign;

		t.reassignRoutes = [];

	},
	checkcoords: function (obj) {
		var t = Tabs.Reassign;
		if (obj.id == 'pbok') {
			t.check = true;
			t.addReassignRoute();
		}
		return;
	},
	addReassignRoute: function () {
		var t = Tabs.Reassign;
		
		try {
		
		var city = t.tcp.city.id;
		if (t.tcpto.city == null) return;
		if (t.tcp.city.id == t.tcpto.city.id) return;
		t.check = false;
		var SendSupplyTroop = ById('pbSupplyTroops').checked;
		var SendMilitiaman = ById('pbMilitiaman').checked;
		var SendScout = ById('pbScout').checked;
		var SendPikeman = ById('pbPikeman').checked;
		var SendSwordsman = ById('pbSwordsman').checked;
		var SendArchers = ById('pbArcher').checked;
		var SendCavalry = ById('pbCavalry').checked;
		var SendHeavyCavalry = ById('pbHeavyCavalry').checked;
		var SendSupplyWagons = ById('pbSupplyWagon').checked;
		var SendBallista = ById('pbBallista').checked;
		var SendBatteringRam = ById('pbBatteringRam').checked;
		var SendCatapult = ById('pbCatapult').checked;
		var SendBloodThom = ById('pbBloodThom').checked;
		var SendExecutioner = ById('pbExecutioner').checked;
		var SendSiegeWall = ById('pbSiegeWall').checked;
		var SendFlameArcher = ById('pbFlameArcher').checked;
		var SendHusar = ById('pbHusar').checked;
		
		var SupplyTroop = ById('pbtargetSupplyTroops').value;
		var Militiaman = ById('pbtargetMilitiaman').value;
		var Scout = ById('pbtargetScout').value;
		var Pikeman = ById('pbtargetPikeman').value;
		var Swordsman = ById('pbtargetSwordsman').value;
		var Archers = ById('pbtargetArcher').value;
		var Cavalry = ById('pbtargetCavalry').value;
		var HeavyCavalry = ById('pbtargetHeavyCavalry').value;
		var SupplyWagons = ById('pbtargetSupplyWagon').value;
		var Ballista = ById('pbtargetBallista').value;
		var BatteringRam = ById('pbtargetBatteringRam').value;
		var Catapult = ById('pbtargetCatapult').value;
		var BloodThom = ById("pbtargetBloodThom").value;
		var Executioner = ById("pbtargetExecutioner").value;
		var SiegeWall = ById("pbtargetSiegeWall").value;
		var FlameArcher = ById("pbtargetFlameArcher").value;
		var Husar = ById("pbtargetHusar").value;
		
		var target_x = t.tcpto.city.x;
		var target_y = t.tcpto.city.y;

		var lRE = t.reassignRoutes;
		lRE.push({
			city: city,
			city_to: t.tcpto.city.id,
			target_x: target_x,
			target_y: target_y,
			SendSupplyTroop: SendSupplyTroop,
			SupplyTroop: SupplyTroop,
			SendMilitiaman: SendMilitiaman,
			Militiaman: Militiaman,
			SendScout: SendScout,
			Scout: Scout,
			SendPikeman: SendPikeman,
			Pikeman: Pikeman,
			SendSwordsman: SendSwordsman,
			Swordsman: Swordsman,
			SendArchers: SendArchers,
			Archers: Archers,
			SendCavalry: SendCavalry,
			Cavalry: Cavalry,
			SendHeavyCavalry: SendHeavyCavalry,
			HeavyCavalry: HeavyCavalry,
			SendSupplyWagons: SendSupplyWagons,
			SupplyWagons: SupplyWagons,
			SendBallista: SendBallista,
			Ballista: Ballista,
			SendBatteringRam: SendBatteringRam,
			BatteringRam: BatteringRam,
			SendCatapult: SendCatapult,
			Catapult: Catapult,
			SendBloodThom: SendBloodThom,
			BloodThom: BloodThom,
			SendExecutioner: SendExecutioner,
			Executioner: Executioner,
			SendSiegeWall: SendSiegeWall,
			SiegeWall: SiegeWall,
			SendFlameArcher: SendFlameArcher,
			FlameArcher: FlameArcher,
			SendHusar: SendHusar,
			Husar: Husar,
		});
		ById('pbReassignDivD').style.background = '#99FF99';
		setTimeout(function () {
			(ById('pbReassignDivD').style.background = '');
		}, 1000);
	} catch (ex) {
					alert('16231/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
	}
	},
	showReassignRoutes: function () {
		var t = Tabs.Reassign;
		var popReassignRoutes = null;
		t.popReassignRoutes = new CPopup('pbShowTrade', 0, 0, 1100, 500, true, function () {
			clearTimeout(1000);
		});
		var m = '<DIV style="max-height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowReassignRoutes" id="pbRoutesQueue">';
		t.popReassignRoutes.getMainDiv().innerHTML = '</table></div>' + m;
		t.popReassignRoutes.getTopDiv().innerHTML = '<div class="popupBanner">' + culang.reassignAutoHeadRoutes + '</div>';
		t.paintReassignRoutes();
		t._addTabHeader();
		t.popReassignRoutes.show(true);
	},
	paintReassignRoutes: function () {
		var t = Tabs.Reassign;
		var r = t.reassignRoutes;
		var cityname;
		var cityto;
		for (var i = (r.length - 1); i >= 0; i--) {
			for (var y = 0; y < Seed.cities.length; y++) {
				if (parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
				if (r[i].city_to) 
					if (parseInt(Seed.cities[y][0]) == r[i].city_to) var cityto = Seed.cities[y][1];
			}
			var queueId = i;
			if (!r[i].city_to) cityto = r[i].target_x + ',' + r[i].target_y;
			t._addTab(queueId, cityname, cityto, r[i].SendSupplyTroop, r[i].SupplyTroop, r[i].SendMilitiaman, r[i].Militiaman, r[i].SendScout, r[i].Scout, r[i].SendPikeman, r[i].Pikeman, r[i].SendSwordsman, r[i].Swordsman, r[i].SendArchers, r[i].Archers, r[i].SendCavalry, r[i].Cavalry, r[i].SendHeavyCavalry, r[i].HeavyCavalry, r[i].SendSupplyWagons, r[i].SupplyWagons, r[i].SendBallista, r[i].Ballista, r[i].SendBatteringRam, r[i].BatteringRam, r[i].SendCatapult, r[i].Catapult, r[i].SendBloodThom, r[i].BloodThom, r[i].SendExecutioner, r[i].Executioner, r[i].SendSiegeWall, r[i].SiegeWall,  r[i].SendFlameArcher, r[i].FlameArcher, r[i].SendHusar, r[i].Husar);
		}
	},

	_addTab: function (queueId, cityname, cityto, SendSupplyTroop, SupplyTroop, SendMilitiaman, Militiaman, SendScout, Scout, SendPikeman, Pikeman, SendSwordsman, Swordsman, SendArchers, Archers, SendCavalry, Cavalry, SendHeavyCavalry, HeavyCavalry, SendSupplyWagons, SupplyWagons, SendBallista, Ballista, SendBatteringRam, BatteringRam, SendCatapult, Catapult, SendBloodThom, BloodThom, SendExecutioner, Executioner,SendSiegeWall, SiegeWall, SendFlameArcher, FlameArcher, SendHusar, Husar) {
		var t = Tabs.Reassign;
		var row = ById('pbRoutesQueue').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = queueId;
		row.insertCell(1).innerHTML = cityname;
		row.insertCell(2).innerHTML = cityto;
		row.insertCell(3).innerHTML = SendSupplyTroop + '<br>' + addCommas(SupplyTroop);
		row.insertCell(4).innerHTML = SendMilitiaman + '<br>' + addCommas(Militiaman);
		row.insertCell(5).innerHTML = SendScout + '<br>' + addCommas(Scout);
		row.insertCell(6).innerHTML = SendPikeman + '<br>' + addCommas(Pikeman);
		row.insertCell(7).innerHTML = SendSwordsman + '<br>' + addCommas(Swordsman);
		row.insertCell(8).innerHTML = SendArchers + '<br>' + addCommas(Archers);
		row.insertCell(9).innerHTML = SendCavalry + '<br>' + addCommas(Cavalry);
		row.insertCell(10).innerHTML = SendHeavyCavalry + '<br>' + addCommas(HeavyCavalry);
		row.insertCell(11).innerHTML = SendSupplyWagons + '<br>' + addCommas(SupplyWagons);
		row.insertCell(12).innerHTML = SendBallista + '<br>' + addCommas(Ballista);
		row.insertCell(13).innerHTML = SendBatteringRam + '<br>' + addCommas(BatteringRam);
		row.insertCell(14).innerHTML = SendCatapult + '<br>' + addCommas(Catapult);
		row.insertCell(15).innerHTML = SendBloodThom + '<br>' + addCommas(BloodThom);
		row.insertCell(16).innerHTML = SendExecutioner + '<br>' + addCommas(Executioner);
		row.insertCell(17).innerHTML = SendSiegeWall + '<br>' + addCommas(SiegeWall);
		row.insertCell(18).innerHTML = SendFlameArcher + '<br>' + addCommas(FlameArcher);	
		row.insertCell(19).innerHTML = SendHusar + '<br>' + addCommas(Husar);	
		row.insertCell(20).innerHTML = '<a id="tradecancel_' + queueId + '"><span><img src="' + IMGdeleteButton + '" border=0 title="' + culang.mainDelete + '" alt="' + culang.mainDelete + '"></span></a>';
		
		ById('tradecancel_' + queueId).addEventListener('click', function () {
			t.cancelQueueElement(queueId);
		}, false);
	},

	_addTabHeader: function () {
		var t = Tabs.Reassign;
		var row = ById('pbRoutesQueue').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = "ID";
		row.insertCell(1).innerHTML = culang.reassignAutoLogOK;
		row.insertCell(2).innerHTML = culang.reassignAutoLogOK2;
		row.insertCell(3).innerHTML = '<img title="' + uW.unitcost['unt1'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_1_30.jpg>';
		row.insertCell(4).innerHTML = '<img title="' + uW.unitcost['unt2'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_2_30.jpg>';
		row.insertCell(5).innerHTML = '<img title="' + uW.unitcost['unt3'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_3_30.jpg>';
		row.insertCell(6).innerHTML = '<img title="' + uW.unitcost['unt4'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_4_30.jpg>';
		row.insertCell(7).innerHTML = '<img title="' + uW.unitcost['unt5'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_5_30.jpg>';
		row.insertCell(8).innerHTML = '<img title="' + uW.unitcost['unt6'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_6_30.jpg>';
		row.insertCell(9).innerHTML = '<img title="' + uW.unitcost['unt7'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_7_30.jpg>';
		row.insertCell(10).innerHTML = '<img title="' + uW.unitcost['unt8'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_8_30.jpg>';
		row.insertCell(11).innerHTML = '<img title="' + uW.unitcost['unt9'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_9_30.jpg>';
		row.insertCell(12).innerHTML = '<img title="' + uW.unitcost['unt10'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_10_30.jpg>';
		row.insertCell(13).innerHTML = '<img title="' + uW.unitcost['unt11'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_11_30.jpg>';
		row.insertCell(14).innerHTML = '<img title="' + uW.unitcost['unt12'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_12_30.jpg>';
		row.insertCell(15).innerHTML = '<img title="' + uW.unitcost['unt13'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_13_30.jpg>';
		row.insertCell(16).innerHTML = '<img title="' + uW.unitcost['unt14'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_14_30.jpg>';
		row.insertCell(17).innerHTML = '<img title="' + uW.unitcost['unt15'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_15_30.jpg>';
		row.insertCell(18).innerHTML = '<img title="' + uW.unitcost['unt16'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_16_30.jpg>';
		row.insertCell(19).innerHTML = '<img title="' + uW.unitcost['unt17'][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_17_30.jpg>';
		row.insertCell(20).innerHTML = culang.mainDelete;

	},

	cancelQueueElement: function (queueId) {
		var t = Tabs.Reassign;
		var queueId = parseInt(queueId);
		t.reassignRoutes.splice(queueId, 1);
		t.showReassignRoutes();
	},

	saveReassignRoutes: function () {
		var t = Tabs.Reassign;
		var serverID = getServerId();
		GM_setValue('reassignRoutes_' + serverID, JSON2.stringify(t.reassignRoutes));
	},
	readReassignRoutes: function () {
		var t = Tabs.Reassign;
		var serverID = getServerId();
		s = GM_getValue('reassignRoutes_' + serverID);
		if (s != null) {
			route = JSON2.parse(s);
			for (k in route)
			t.reassignRoutes[k] = route[k];
		}
	},
	saveReassignState: function () {
		var t = Tabs.Reassign;
		var serverID = getServerId();
		GM_setValue('reassignState_' + serverID, JSON2.stringify(t.reassignState));
	},
	readReassignState: function () {
		var t = Tabs.Reassign;
		var serverID = getServerId();
		s = GM_getValue('reassignState_' + serverID);
		if (s != null) {
			state = JSON2.parse(s);
			for (k in state)
			t.reassignState[k] = state[k];
		}
	},
	toggleReassignState: function (obj) {
		var t = Tabs.Reassign;
		obj = ById('pbReassignState');
		if (t.reassignState.running == true) {
			t.reassignState.running = false;
			if (obj) obj.value = culang.mainReassign + "  = " + culang.buttonOFF;
			t.checkdoreassigntimeout = null;
			t.count = 0;
			Options.lastreassign = 0;
			saveOptions();

		} else {
			t.reassignState.running = true;
			if (obj) obj.value = culang.mainReassign + " = " + culang.buttonON;
			t.e_reassignRoutes();
		}
	},

	checkdoReassign: function () {
		var t = Tabs.Reassign;
		t.doReassign(t.count);
		t.count++;
		if (t.count < t.reassignRoutes.length && t.reassignState.running) {
			t.checkdoreassigntimeout = setTimeout(function () {
				t.checkdoReassign();
			}, 5000);
		} else {
			var now = new Date().getTime() / 1000.0;
			now = now.toFixed(0);
			Options.lastreassign = now;
			saveOptions();
			t.count = 0;
		}
	},

	doReassign: function (count,tt) {
		var t = Tabs.Reassign;
try {
		var params = uW.Object.clone(uW.g_ajaxparams);
		if (t.reassignRoutes.length == 0) return;
		var send = [];
		var citytotal = 0;
		var totalsend = 0;
		if (tt != undefined) params.tt = tt;
		var city = t.reassignRoutes[count]["city"];
		if (t.reassignRoutes[count]["city_to"]) {
			var cityto = t.reassignRoutes[count]["city_to"];
			var xcoord = Cities.byID[cityto].x;
			var ycoord = Cities.byID[cityto].y;
		} else {
			var xcoord = t.reassignRoutes[count]["target_x"];
			var ycoord = t.reassignRoutes[count]["target_y"];		
		}
		var cityID = 'city' + city;
		if (!Cities.byID[city]) return;
		var marching = getMarchInfoBOT(cityID);
		t.getRallypoint(cityID);
		var RInfo = getRallypointInfo(city);
		var maxsend = RInfo.maxMarchSize;
		
		totalsend = 0;
		var troopsselect = ["SupplyTroop", "Militiaman", "Scout", "Pikeman", "Swordsman", "Archers", "Cavalry", "HeavyCavalry", "SupplyWagons", "Ballista", "BatteringRam", "Catapult", "BloodThom", "Executioner", "SiegeWall", "FlameArcher", "Husar"];
		try {
		for (k = 0; k < troopsselect.length; k++) {
			if (uW.unitcost['unt' + (k + 1)]) {
				var citytroops = Seed.units[cityID]['unt' + (parseInt(k) + 1)];
				var marchtroops = marching.marchUnits[parseInt(k) + 1];
				citytotal = parseInt(citytroops) + parseInt(marchtroops);
				if (t.reassignRoutes[count]['Send' + troopsselect[k]] == false) {
					continue;
				}
				if (citytotal > t.reassignRoutes[count][troopsselect[k]]) {
					var sendtroops = parseInt(citytotal) - parseInt(t.reassignRoutes[count][troopsselect[k]]);
					if (parseInt(sendtroops) > parseInt(citytroops)) sendtroops = citytroops;
					if (parseInt(sendtroops) < 0) sendtroops = 0;
					send[(parseInt(k) + 1)] = sendtroops;
					totalsend += parseInt(send[(parseInt(k) + 1)]);

				}
				if (totalsend > maxsend) {
					totalsend -= send[(parseInt(k) + 1)];
					send[(parseInt(k) + 1)] = parseInt(maxsend - totalsend);
					totalsend += parseInt(send[(parseInt(k) + 1)]);
					break;
				}
			} else {
				send[(parseInt(k) + 1)] = 0;
			}
		}
		} catch(ex) {
								alert('16450/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
		for (var zz = 0; zz < Seed.cities.length; zz++) {
			if (parseInt(Seed.cities[zz][0]) == city) var cityname = Seed.cities[zz][1];
		}

		params.cid = city;
		params.type = "5";
		params.kid = 0;
		params.xcoord = xcoord;
		params.ycoord = ycoord;
		params.g = 0;
		params.r1 = 0;
		params.r2 = 0;
		params.r3 = 0;
		params.r4 = 0;
		params.r5 = 0;
		for (k = 1; k <= troopsselect.length; k++) {
			if (parseIntNan(send[k]) > 0) params["u" + k] = parseIntNan(send[k]);
		}
		if (totalsend > 0) {
			new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function (transport) {
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.ok) {
						var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
						var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
						var ut = uW.unixtime();
						var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
						for(i = 0; i <= unitsarr.length; i++){
							if(params["u"+i]){
								unitsarr[i] = params["u"+i];
							}
						}
						var resources=new Array();
						resources[0] = params.gold;
						for(i=1; i<=4; i++){
							resources[i] = params["r"+i];
						}
						var currentcityid = params.cid;
						uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
								 
						if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
					actionLog("" + culang.mainReassign + "", "" + culang.reassignAutoLogOK + " " + cityname + " " + culang.reassignAutoLogOK2 + " " + xcoord + ',' + ycoord + "  ->   " + culang.mainTroops + ": <span class='boldRed'>" + totalsend + "</span>");
					} else {
						if (rslt.user_action) {
							if (rslt.user_action == "backOffWaitTime") {
								var t = Tabs.Reassign;
								var tt = null;
								if (rslt.tt) tt = rslt.tt;
								var wait = 1;
								if (rslt.wait_time) wait = rslt.wait_time;
								setTimeout(function () {
									t.doReassign(count, tt);
								}, wait * 1000);
								return;
							} else {
								actionLog("" + culang.mainReassign + "", "<b><font color=red>alert " + rslt.user_action + " </font></b>");
							}
						} else {
							actionLog("" + culang.mainReassign + "", "From: " + cityname + " to : " + xcoord + ',' + ycoord + " -> <span class=boldRed>" + rsltErrorCode(rslt) + "</span>");
						}
					}
				},
				onFailure: function (transport) {
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.user_action) {
						actionLog("" + culang.mainReassign + "", "<b><font color=red>" + culang.movementCaptchaAlert + "</font></b>");
						new CdialogCancelContinue('<SPAN class=boldRed>' + culang.reassignCaptchaAlert + '</span>', null, null, mainPop.getMainDiv);
					} else {
						actionLog("" + culang.mainReassign + "", "<SPAN class=boldRed>" + transport.responseText + "</span>");

					}
				}
			});
		}
} catch (ex) {
					alert('16530/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
}
	},
	show: function () {
		var t = Tabs.Reassign;
	},
	hide: function () {
		var t = Tabs.Reassign;
	},
	onUnload: function () {
		var t = Tabs.Reassign;
		if (!ResetAll) t.saveReassignRoutes();
		if (!ResetAll) t.saveReassignState();
	},

	showManuel: function () {
		var t = Tabs.Reassign;
		var ModelCity = {};
		var rownum = 0;
		var rownum2 = 0;

		function _row(name, row, noTotal) {
			if (rownum++ % 2) style = '';
			else style = ' style = "background: #e8e8e8"';
			var tot = 0;
			var m = [];
			m.push('<TR style="background: #fff" align=right');
			m.push(style);
			m.push('><TD');
			m.push(style);
			m.push('><B>');
			m.push(name);
			m.push('</td>');
			if (noTotal) {
				m.push('<TD');
				m.push(style);
				m.push('>&nbsp;</td>');
			} else {
				for (i = 0; i < row.length; i++)
				tot += row[i];
				m.push('<TD style="background: #ffc">');
				m.push(addCommas(tot));
				m.push('</td>');
			}
			for (i = 0; i < row.length; i++) {
				m.push('<TD');
				m.push(style);
				m.push('>');
				m.push(addCommas(row[i]));
				m.push('</td>');
			}
			m.push('</tr>');
			return m.join('');
		}
		if (t.state == null) {
			m = "<DIV class=pdxStat>" + culang.reassignHead + "</div>";
			m += "<div id='ptREAStatus' style='text-align:center;overflow-y:auto; max-height:30px; border-bottom:1px solid #141516;'></div>";
			m += "<TABLE width='95%' class=pdxTab border=0 align=left>\
        <tr align=center valign=middle><td colspan=1 width=100><b><u>" + culang.mainCastle + "</b></u><br><span id=REAsrcRptspeedcity></span></td>\
        <td colspan=1 width='100px'><input type=button style='font-weight:bold' id=REAaction value='" + culang.mainReassign + "'></td>\
        <td colspan=1 width='100px'><b><u>" + culang.mainTarget + "</b></u><br><span id=REAdesRptspeedcity></span></td><td width=150 colspan=1><b><u>" + culang.reassignEST + "</b></u><br>&nbsp;" + culang.mainDistance + ": <span id='KsEstimationREAD'>&nbsp;</span></td></tr>\
        <tr align=center valign=top><td width=100><div id=REAstatsource></div></td>\
        <td ><table cellspacing=0 cellpadding=0 width=99%>";
			for (r = 1; r < 18; r++) {
				if (rownum++ % 2) style = '';
				else style = ' style = "background: #e8e8e8"';
				m += '<tr ' + style + '><td  align=right><img height=20 title="' + uW.unitcost['unt' + r][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + r + '_30.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="REAnbunit' + r + '" type=text size=7 value="0"></td></tr>';
			}

			m += "</table></td><td><div id=REAstatdest></div></td>";
			m += "<td colspan=2><table cellspacing=0 cellpadding=0 width=80%>";
			rownum = 0;
			for (r = 1; r < 18; r++) {
				if (rownum++ % 2) style = '';
				else style = 'background: #e8e8e8;';
				m += '<tr style="' + style + ' height:16px;font-size:11px;"><td width=50% height=20 align=center><span id="KsEstimationREAZ' + r + '">&nbsp;</span></td></tr>';
			}
			m += "</tr></table>";
			m += "</tr><tr><td colspan=4><center><b>" + culang.mainKnights + "</b>: <SELECT id='REApiKnight' type=list></center></tr><tr><td colspan=4><div class='pdxStat'>" + culang.reassignHeadStats + "</div><div id='statpourREA'></div></td></tr></table>";
			t.ReassignDiv.innerHTML = m;
			t.statpourREA = document.getElementById('statpourREA');
			t.statutREA = document.getElementById('ptREAStatus');
			t.actionREA = document.getElementById('REAaction');
			t.actionREA.addEventListener('click', function () {t.clickReassigneDo();}, false);
			var dcp1 = new CdispCityPicker('ptREA1', ById('REAdesRptspeedcity'), false, t.clickREACityDestinationSelect, 1);
			var dcp0 = new CdispCityPicker('ptREA0', ById('REAsrcRptspeedcity'), false, t.clickREACitySourceSelect, Cities.byID[uW.currentcityid].idx);
			t.state = 1;
			t.estimerTemps();
		}
		rows = [];
		rows[0] = [];
		m = "<TABLE class=ptTabLined cellspacing=0><TR valign=top align=right><TD width=20></td><TD width=88 style='background: #ffc'><B>" + culang.mainHTotal + "</b></td>";
		for (i = 0; i < Cities.numCities; i++) {
			m += '<TD width=81><B>' + Cities.cities[i].name.substring(0, 10) + '</b></td>';
		}
		for (r = 1; r < 18; r++) {
			rows[r] = [];
			for (i = 0; i < Cities.numCities; i++) {
				cityID = 'city' + Cities.cities[i].id;
				rows[r][i] = parseIntNan(Seed.units[cityID]['unt' + r]);
			}
		}
		for (r = 1; r < 18; r++) {
			m += _row('<img height=18 title="' + uW.unitcost['unt' + r][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + r + '_30.jpg>', rows[r]);
		}
		row = [];
		for (i = 0; i < Cities.numCities; i++) {
			var cityId = 'city' + Cities.cities[i].id;
			var RInfo = getRallypointInfo(Cities.cities[i].id);
			var maxsend = RInfo.maxMarchSize;
			var slots = RInfo.usedSlots;
			var niveauPointRall = RInfo.maxMarches;
			row[i] = '<SPAN><B>' + slots + '/' + niveauPointRall + '</b></span>';
		}
		m += _row('' + culang.mainSRallyPoint + '', row, true, 0);
		m += "</table>";
		t.statpourREA.innerHTML = m;
		clearTimeout(t.displayTimer);
		t.displayTimer = setTimeout(t.showManuel, 4000);
	},
	estimerTemps: function () {
		var t = Tabs.Reassign;
		var x1 = parseInt(t.sourceCity.x);
		var x2 = parseInt(t.destinationCity.x);
		var y1 = parseInt(t.sourceCity.y);
		var y2 = parseInt(t.destinationCity.y);
		var dist = distance(x1, y1, x2, y2);
		ById("KsEstimationREAD").innerHTML = "<b>" + dist + "</b>";
		for (r = 1; r < 18; r++) {
			var m = estETA(dist, r, t.sourceCity.id, 5);
			ById("KsEstimationREAZ" + r).innerHTML = "<span class='boldRed'>" + m.friendEtaStr + "</span>";
		}
	},
	clickReassigneDo: function (tt) {
		var t = Tabs.Reassign;
		t.statutREA.innerHTML = '';
		var totalunit = 0;
		for (r = 1; r < 18; r++) {
			if (parseInt(ById("REAnbunit" + r).value) > parseInt(ById("REAdestunit" + r).value)) {
				ById("REAnbunit" + r).style.backgroundColor = "red";
				return false;
			}
			totalunit = totalunit + parseIntNan(ById("REAnbunit" + r).value);
			ById("REAnbunit" + r).style.backgroundColor = "";
		}
		if (t.sourceCity.id == t.destinationCity.id) {
			t.statutREA.innerHTML = '<FONT COLOR=#550000>' + culang.reassignSameCity + '</font>';
			return;
		}
		if (totalunit == 0) {
			t.statutREA.innerHTML = '<FONT COLOR=#550000>' + culang.reassignSelectTroops + '</font>';
			return;
		}
		var RInfo = getRallypointInfo(t.sourceCity.id);
		var maxtroupe = RInfo.maxMarchSize;
		var slots = RInfo.usedSlots;
		var niveauPointRall = RInfo.maxMarchSize;
		if (totalunit > maxtroupe) {
			t.statutREA.innerHTML = '<FONT COLOR=#550000>' + culang.reassignMaxRP + ' ' + maxtroupe + ' ' + culang.reassignMaxRP2 + '</font>';
			return;
		}
		t.actionREA.disabled = true;
		var x = t.destinationCity.x;
		var y = t.destinationCity.y;
		var params = uW.Object.clone(uW.g_ajaxparams);
		if (tt != undefined) params.tt = tt;
		for (var i = 1; i<18; i++) {
			if (ById("REAnbunit"+i).value > 0) {
				params['u'+i] = parseIntNan(ById("REAnbunit"+i).value);
			}
		}
		params.cid = t.sourceCity.id;
		params.type = "5";
		params.kid = ById("REApiKnight").value;
		params.xcoord = x;
		params.ycoord = y;
		params.g = 0;
		params.r1 = 0;
		params.r2 = 0;
		params.r3 = 0;
		params.r4 = 0;
		params.r5 = 0;
		t.statutREA.innerHTML = "<font size='2px'><b><i>" + culang.reassignLoading + "</i></b></font>";
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var t = Tabs.Reassign;
				var rslt = transport;
				if (rslt.ok) {
					var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
          var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
							unitsarr[i] = params["u"+i];
						}
					}
					var resources=new Array();
					resources[0] = params.gold;
					for(i=1; i<=4; i++){
						resources[i] = params["r"+i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
					t.clickREACitySourceSelect(t.sourceCity);
					t.statutREA.innerHTML = "<font size='2px'><b>" + culang.reassignOK + " " + timestr(timediff) + "</font>";
					t.actionREA.disabled = false;
				} else {
					if (rslt.user_action == "backOffWaitTime") {
						if (rslt.tt) var tt = rslt.tt;
						var wait = 1;
						if (rslt.wait_time) wait = rslt.wait_time;
						setTimeout(function () {
							t.clickReassigneDo(tt);
						}, wait * 1000);
						return;
					}
					t.statutREA.innerHTML = "<font color=red size='2px'>" + culang.reassignError + "</font>";
					if (rslt.msg) {
						t.statutREA.innerHTML += "<br><font color=black size='2px'>" + rslt.msg + "</font>";
						t.actionREA.disabled = false;
					} else {
						t.statutREA.innerHTML += "<br>" + culang.reassignIn2Minutes + "</font>";
						setTimeout(function () {
							t.clickReassigneDo();
						}, 2000);
					}
				}
			},
			onFailure: function () {
				var t = Tabs.Reassign;
				t.statutREA.innerHTML = "<font color=red>" + culang.reassignError + "</font>";
				t.actionREA.disabled = false;
			}
		});
	},
	clickREACitySourceSelect: function (city) {
		var t = Tabs.Reassign;
		var rownum = 0;
		if (t.sourceCity != city) {
			t.sourceCity = city;
			for (r = 1; r < 18; r++) {
				ById("REAnbunit" + r).value = "0";
			}
		} else {
			var cityID = 'city' + t.sourceCity.id;
			for (r = 1; r < 18; r++) {
				if (parseInt(Seed.units[cityID]['unt' + r]) < ById("REAnbunit" + r).value) ById("REAnbunit" + r).value = "0";
			}
		}
		t.actionREA.disabled = false;
		var m = "";
		m = "<table cellspacing=0 cellpadding=0 width=80%>";
		var cityID = 'city' + t.sourceCity.id;
		for (r = 1; r < 18; r++) {
			if (rownum++ % 2) style = '';
			else style = 'background: #e8e8e8;';
			m += '<tr style="' + style + '"><td align=right><img title="' + uW.unitcost['unt' + r][0] + '" height=20 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + r + '_30.jpg></td>\
           <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="REAdestunit' + r + '" type=text size=7 readonly value="' + parseIntNan(Seed.units[cityID]['unt' + r]) + '">&nbsp;\
           <input type=button value="->" id="REApdestunit' + r + '"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
		}
		m += "</table>";
		ById("REAstatsource").innerHTML = m;
		var knt = new Array();
		ById('REApiKnight').innerHTML = "";
		var o = document.createElement("option");
		o.text = uW.g_js_strings.modal_attack.dchooseknightd;
		o.value = 0;
		ById("REApiKnight").options.add(o);
		for (k in Seed.knights['city' + t.sourceCity.id]) {
			if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]) {
				knt.push({
					Name: Seed.knights['city' + t.sourceCity.id][k]["knightName"],
					Combat: Seed.knights['city' + t.sourceCity.id][k]["combat"],
					ID: Seed.knights['city' + t.sourceCity.id][k]["knightId"],
				});
			}
		}
		knt = knt.sort(function sort(a, b) {
			a = parseInt(a['Combat']);
			b = parseInt(b['Combat']);
			return a == b ? 0 : (a > b ? -1 : 1);
		});
		for (k in knt) {
			if (knt[k]["Name"] != undefined) {
				var o = document.createElement("option");
				o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] + ')')
				o.value = knt[k]["ID"];
				ById("REApiKnight").options.add(o);
			}
		}
		for (r = 1; r < 18; r++) {
			ById("REApdestunit" + r).addEventListener('click', function () {
				var nomcha = this.id.replace("REApdest", "REAdest");
				var nomcha2 = this.id.replace("REApdestunit", "REAnbunit");
				ById(nomcha2).value = 0;
				var RInfo = getRallypointInfo(t.sourceCity.id);
				var maxtroupe = RInfo.maxMarchSize;
				var slots = RInfo.usedSlots;
				var niveauPointRall = RInfo.maxMarchSize;
				var nbunitto = 0;
				for (r = 1; r < 18; r++) {
					nbunitto += parseIntNan(ById("REAnbunit" + r).value);
				}
				var libre = parseInt(maxtroupe - nbunitto);
				if (ById(nomcha).value >= libre) {
					ById(nomcha2).value = libre;
				} else {
					ById(nomcha2).value = ById(nomcha).value;
				}
			}, false);
		}
		t.estimerTemps();
	},
	clickREACityDestinationSelect: function (city) {
		var t = Tabs.Reassign;
		var rownum = 0;
		t.destinationCity = city;
		var m = "";
		m = "<table cellspacing=0 cellpadding=0 width=80%>";
		for (r = 1; r < 18; r++) {
			if (rownum++ % 2) style = '';
			else style = 'background: #e8e8e8;';
			cityID = 'city' + t.destinationCity.id;
			m += '<tr style="' + style + '"><td align=right><img height=20 title="' + uW.unitcost['unt' + r][0] + '" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + r + '_30.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" type=text size=7 readonly value="' + parseIntNan(Seed.units[cityID]['unt' + r]) + '"></td></tr>';
		}
		m += "</table>";
		ById("REAstatdest").innerHTML = m;
		t.estimerTemps();
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/AutoTrain.js">
//	
//	   KOC POWER - TABS AUTOTRAIN										        
//	

var TrainOptions={
	throneCheck:false,
	throneSet:1,
	Running: false,
	list:{},
	Item:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	listactif:{},
	listlabour:{},
	timelauch:60,
	unitemin:{},
	unitemax:{},
	listboost:{},
	ascension: {},
	UnitMixValue:100,
	Workers:{1:100,2:100,3:100,4:100,5:100,6:100,7:100,8:100},
	Keep:{1:{Food:0,Wood:0,Stone:0,Ore:0},
				2:{Food:0,Wood:0,Stone:0,Ore:0},
				3:{Food:0,Wood:0,Stone:0,Ore:0},
				4:{Food:0,Wood:0,Stone:0,Ore:0},
				5:{Food:0,Wood:0,Stone:0,Ore:0},
				6:{Food:0,Wood:0,Stone:0,Ore:0},
				7:{Food:0,Wood:0,Stone:0,Ore:0},
				8:{Food:0,Wood:0,Stone:0,Ore:0}},
	Resource:{1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true},
	doTraps:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
	doCalrops:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
	doSpikes:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
	doXbows:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
	doTrebu:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
	troopType:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	keepFood:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	keepWood:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	keepStone:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	keepOre:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
	AsTroops: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0},
	AsMaxTroops: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0},
	AsEnabled: {1: false,2: false,3: false,4: false,5: false,6: false,7: false,8: false},
	AsSelectMax: {1: false,	2: false,3: false,4: false,5: false,6: false,7: false,8: false},
	AsMax: {1: 0,	2: 0,	3: 0,	4: 0,	5: 0,	6: 0,	7: 0,	8: 0},
}
Tabs.AutoTrain = {
	tabOrder: TabOptions.toAutoTrain,
	tabLabel: culang.tabLabelAutoTrain,
	cont: null,
	nbfil: 0,
	crfil: 0,
	timer: null,
	city: 0,
	numcity: -1,
	options: {
		running: false,
	},
	id: {},
	readOptions: function () {
		var t = Tabs.AutoTrain;
		var a = getServerId();
		var u = getMyUserId();
		var s = GM_getValue("TrainingData_" + a + "_" + u);
		if (s != null) {
			opts = JSON2.parse(s);
			for (k in opts) {
				t.options[k] = opts[k];
			}
		}
	},
	saveOptions: function () {
		var t = Tabs.AutoTrain;
		var a = getServerId();
		var u = getMyUserId();
		setTimeout(function () {
			GM_setValue("TrainingData_" + a + "_" + u, JSON2.stringify(t.options));
		}, 0)
	},
	getTrainingQueue: function (cityId) {
		var t = Tabs.AutoTrain;
		var c = 0,
			d = 0,
			ret = {};
		var q = Seed.queue_unt['city' + cityId];
		for (var i = 0; i < q.length; i++) {
			if (q[i][7]) {
				d++;
			} else {
				c++;
			}
		}
		ret.normal = c;
		ret.ascension = d;
		return ret;
	},
	getEmptyQueue: function (cityId, numbat) { // numbat = 13=casenre 22druide/24fey
		var t = Tabs.AutoTrain;
		var barracksTotal = getCityBuilding(cityId, numbat).count;
		if (numbat == 22 || numbat == 24 || numbat == 26) {
			availableTrainingSlots = barracksTotal - t.getTrainingQueue(cityId).ascension;
		} else {
			availableTrainingSlots = barracksTotal - t.getTrainingQueue(cityId).normal;
		}
		return availableTrainingSlots;
	},
	init: function (div) {
		var t = Tabs.AutoTrain;
		t.cont = div;
		t.readOptions();
		t.state = null;
		AutoTrainObj = ById('pbAutoTrainState');
		if (TrainOptions.Running == false) {
			if (AutoTrainObj) AutoTrainObj.value = culang.buttonAutoTrain + " = " + culang.buttonOFF;
		} else {
			if (AutoTrainObj) AutoTrainObj.value = culang.buttonAutoTrain + " = " + culang.buttonON;
			t.timer = setTimeout(t.Start, 5000);
		}
		if (TrainOptions.timelauch < 3) {
			TrainOptions.timelauch = 3;
			saveTrainingOptions();
		}
		return t.cont;
	},
	Start: function () {
		var t = Tabs.AutoTrain;
			if (!TrainOptions.Running) {
				clearTimeout(t.timer);
				return;
			}
			if (TrainOptions.throneCheck && Seed.throne.activeSlot != TrainOptions.throneSet) {
				actionLog(culang.tabLabelAutoTrain, culang.mainWrongThroneSet); //15.10.2012 Bommel
				clearTimeout(t.timer);
				t.timer = setTimeout(t.Start, parseIntNan(TrainOptions.timelauch * 60) * 1000);
				return;
			}
			if (t.numcity < Cities.numCities - 1) {
				t.numcity++;
			} else {
				t.numcity = -1;
				clearTimeout(t.timer);
				t.timer = setTimeout(t.Start, parseIntNan(TrainOptions.timelauch * 60) * 1000);
				return;
			}
			var c = t.numcity;
			var cityId = Cities.cities[c].id;
			if (!TrainOptions.listactif[cityId]) {
				clearTimeout(t.timer);
				t.timer = setTimeout(function () { t.Start(); }, 1000);
				return;
			}
			var populationdispo = 0;
			if (!TrainOptions.listlabour[cityId]) {
				populationdispo = parseIntNan(Seed.citystats['city' + cityId].pop[0]) - parseIntNan(Seed.citystats['city' + cityId].pop[3]);
			} else {
				populationdispo = parseIntNan(Seed.citystats['city' + cityId].pop[0]).toFixed(0);
			}
			var availableTrainingSlots = t.getEmptyQueue(cityId, 13);
			maxunite = t.unitemax(cityId, TrainOptions.list[Cities.cities[c].id], (c + 1));
			var resources = t.checkresources(cityId, c);
			var barracks2 = 0;
			if (TrainOptions.AsEnabled[c + 1]) {
				if (Seed.cityData.city[cityId].isPrestigeCity) {
					var atype = Seed.cityData.city[cityId].prestigeInfo.prestigeType;
					if (atype == 1) {
						var barracks2 = t.getEmptyQueue(cityId, 22);
						var unitIdAsc = 13;
						if (barracks2 > 0) maxunite = t.unitemax(cityId, unitIdAsc, (c + 1));
						var resources = t.checkresources(cityId, c);
					} else if (atype == 2) {
						var barracks2 = t.getEmptyQueue(cityId, 24);
						var unitIdAsc = 14;
						if (barracks2 > 0) maxunite = t.unitemax(cityId, unitIdAsc, (c + 1));
						var resources = t.checkresources(cityId, c);
					} else if (atype == 3) {
						var barracks2 = t.getEmptyQueue(cityId, 26);
						var unitIdAsc = 15;
						var resources = t.checkresources(cityId, c);
						if (barracks2 > 0) maxunite = t.unitemax(cityId, unitIdAsc, (c + 1));
					} else {
						var barracks2 = 0;
					}
				}
			}
			if (!resources) {
				actionLog(culang.tabLabelAutoTrain,Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogResError+" <span class='boldGreen'>"+maxunite+"</span> "+culang.autoTrainActionLogResError2+" <span class='boldRed'>"+parseInt(TrainOptions.unitemin[Cities.cities[c].id])+"</span> "+culang.autoTrainActionLogResError3+" ");
				//return;
			} else if ((!TrainOptions.AsEnabled[c + 1] && availableTrainingSlots == 0) || (TrainOptions.AsEnabled[c + 1] && availableTrainingSlots + barracks2 == 0)) {
				actionLog(culang.tabLabelAutoTrain,Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogSlotError+"");
				//return;
			} else if ((maxunite >= parseIntNan(TrainOptions.unitemin[Cities.cities[c].id])) || (TrainOptions.AsEnabled[c + 1] && maxunite >= parseInt(TrainOptions.AsTroops[c + 1]) && barracks2 > 0)) {
				var unitId = TrainOptions.list[cityId];
				var num = parseInt(maxunite);
				if (barracks2 != 0 && TrainOptions.AsEnabled[c + 1]) {
					unitId = unitIdAsc;
					gam = 0;
					if (num >= parseInt(TrainOptions.AsMaxTroops[c + 1])) num = parseInt(TrainOptions.AsMaxTroops[c + 1]);
				} else {
					if (TrainOptions.unitemax[Cities.cities[c].id] != undefined) {
						var maxnum = TrainOptions.unitemax[Cities.cities[c].id];
						if (num > parseInt(maxnum)) num = parseInt(TrainOptions.unitemax[Cities.cities[c].id]);
					}
					var gam = TrainOptions.listboost[cityId];
				}
				var time = uW.modal_barracks_traintime(unitId, num);
				var params = uW.Object.clone(uW.g_ajaxparams);
				params.cid = cityId;
				params.type = unitId;
				params.quant = num;
				if (parseInt(TrainOptions.Item[(c + 1)])) {
					params.items = TrainOptions.Item[(c + 1)];
				}
				params.gambleId = gam;
				new AjaxRequest(uW.g_ajaxpath + "ajax/train.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					loading: true,
					onSuccess: function (transport) {
						var rslt = eval("(" + transport.responseText + ")");
						if (rslt.ok) {
							var MORE_WITH_LESS_FACTOR = uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().MORE_WITH_LESS, cityId, {
									unitid: params.type
								});
							var resourceFactors = [],
								resourceLost;
							if (gam != null) {
								time = rslt.timeNeeded;
							}
							for (var i = 1; i < 5; i++) {
								if (rslt.gamble) {
									resourceFactors.push(rslt.gamble[i.toString()]);
								} else {
									resourceFactors.push(1);
								}
								resourceLost = Math.ceil(parseInt(uW.unitcost["unt" + unitId][i]) * MORE_WITH_LESS_FACTOR) * 3600 * parseInt(num);
								resourceLost = resourceLost * resourceFactors[i - 1];
								uW.seed.resources["city" + cityId]["rec" + i][0] = parseInt(uW.seed.resources["city" + cityId]["rec" + i][0]) - resourceLost;
							}
							var prestige = false;
							
							var items = uW.unitcost["unt" + unitId];
							if (matTypeof(items[11]) == 'object') {
								for (item in items[11]) {
									var quant = items[11][item];
									Seed.items['i'+item] = Seed.items['i'+item] = quant * num;
									uW.ksoItems[item].subtract(quant * num);
								}
							}
							Seed.citystats["city" + cityId].gold[0] = parseInt(uW.seed.citystats["city" + cityId].gold[0]) - parseInt(uW.unitcost["unt" + unitId][5]) * parseInt(num);
							Seed.citystats["city" + cityId].pop[0] = parseInt(uW.seed.citystats["city" + cityId].pop[0]) - Math.ceil(parseInt(uW.unitcost["unt" + unitId][6]) * MORE_WITH_LESS_FACTOR) * parseInt(num);
							if (unitId > 12 && unitId != 16) {
								prestige = true;
								t.numcity--;
							}
							uW.seed.queue_unt["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, null, prestige]);
							if (rslt.updateSeed) try { uW.update_seed(rslt.updateSeed); } catch (ex) {}
							
							actionLog(culang.tabLabelAutoTrain,Cities.cities[c].name+" - " + num+" "+uW.unitcost['unt'+ unitId][0]+" "+culang.mainOK);
						} else {
							actionLog(culang.tabLabelAutoTrain,Cities.cities[c].name+" - " + num+" "+uW.unitcost['unt'+ unitId][0]+" - <span class=boldRed>("+rslt.error_code+') '+rsltErrorCode(rslt)+"</span>");
						}
					},
					onFailure: function (transport) {
						var rslt = eval("(" + transport.responseText + ")");
						actionLog(culang.tabLabelAutoTrain,Cities.cities[c].name+" - " + num+" "+uW.unitcost['unt'+ unitId][0]+" - <span class=boldRed>("+rslt.error_code+') '+rsltErrorCode(rslt)+"</span>");
					}
				});
			} else {
				var unitId = TrainOptions.list[cityId];
				if (barracks2 != 0 && TrainOptions.AsEnabled[c + 1]) unitId = unitIdAsc;
				if (unitId > 12 && unitId != 16 && TrainOptions.AsEnabled[c + 1]) {
					actionLog(culang.tabLabelAutoTrain, Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogPopResError+" "+maxunite+" "+culang.autoTrainActionLogPopResError2+" "+parseInt(TrainOptions.AsTroops[c + 1]) +" "+uW.unitcost['unt'+ unitId][0] + ' ' + culang.autoTrainTrain);
				} else {
					actionLog(culang.tabLabelAutoTrain, Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogPopResError+" "+maxunite+" "+culang.autoTrainActionLogPopResError2+" "+parseInt(TrainOptions.unitemin[Cities.cities[c].id])+" "+uW.unitcost['unt'+ unitId][0] + ' ' + culang.autoTrainTrain);
				}
			}
			var cityNo = t.numcity + 1;
			if (TrainOptions.doTraps[cityNo])
				setTimeout(function(){t.doAutoTraps(cityNo);}, parseInt(Math.random()*4000)+1000);
			if (TrainOptions.doCalrops[cityNo])
				setTimeout(function(){t.doAutoCaltrops(cityNo);}, parseInt(Math.random()*4000)+1000);
			if (TrainOptions.doSpikes[cityNo])
				setTimeout(function(){t.doAutoSpikes(cityNo);}, parseInt(Math.random()*4000)+1000);
			if (TrainOptions.doXbows[cityNo])
				setTimeout(function(){t.doAutoCrossbows(cityNo);}, parseInt(Math.random()*4000)+1000);
			if (TrainOptions.doTrebu[cityNo])
				setTimeout(function(){t.doAutoTrebu(cityNo);}, parseInt(Math.random()*4000)+1000);
		clearTimeout(t.timer);
		t.timer = setTimeout(function () {t.Start();}, 7000);
	},
	doAutoTraps: function (cityNo) {
		var t = Tabs.AutoTrain;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city' + cityId;
		getWallInfo(cityId, wall);
		availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 3) {
			var food = parseInt(Seed.resources['city' + cityId].rec1[0] / 3600);
			var wood = parseInt(Seed.resources['city' + cityId].rec2[0] / 3600);
			var stone = parseInt(Seed.resources['city' + cityId].rec3[0] / 3600);
			var ore = parseInt(Seed.resources['city' + cityId].rec4[0] / 3600);
			availableSlots = 3 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerTrap = wall.Def60Time;
			if (secsPerTrap && availableSpace > 4 && availableSlots > 0) {
				if (availFood > 400 && availWood > 800 & availStone > 200 & availOre > 400) {
					var numberToTrain = 9999999999;
					if ((availFood / 400) < numberToTrain)
						numberToTrain = parseInt(availFood / 400);
					if ((availWood / 800) < numberToTrain)
						numberToTrain = parseInt(availWood / 800);
					if ((availStone / 200) < numberToTrain)
						numberToTrain = parseInt(availStone / 200);
					if ((availOre / 400) < numberToTrain)
						numberToTrain = parseInt(availOre / 400);
					if (numberToTrain > 10)
						numberToTrain = 10;
					if (availableSpace < 40) {
						numberToTrain = 1;
					}
					actionLog(culang.tabLabelAutoTrain, Cities.byID[cityId].name + ' - ' + culang.autoTrainWall +' ' + numberToTrain + ' ' + uW.fortcost['frt60'][0]);
					doDefTrain(cityId, 0, 60, numberToTrain);
				}
			}
		}
	},
	doAutoCaltrops: function (cityNo) {
		var t = Tabs.AutoTrain;
		var wall = {};
		var cityId = Cities.cities[cityNo - 1].id;
		var cityID = 'city' + cityId;
		getWallInfo(cityId, wall);
		availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 3) {
			var food = parseInt(Seed.resources['city' + cityId].rec1[0] / 3600);
			var wood = parseInt(Seed.resources['city' + cityId].rec2[0] / 3600);
			var stone = parseInt(Seed.resources['city' + cityId].rec3[0] / 3600);
			var ore = parseInt(Seed.resources['city' + cityId].rec4[0] / 3600);
			availableSlots = 3 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerCaltrop = wall.Def61Time;
			if (secsPerCaltrop && availableSpace > 1 && availableSlots > 0) {
				if (availFood > 100 && availOre > 400) {
					var numberToTrain = 9999999999;
					if ((availFood / 100) < numberToTrain)
						numberToTrain = parseInt(availFood / 100);
					if ((availOre / 400) < numberToTrain)
						numberToTrain = parseInt(availOre / 400);
					if (numberToTrain > 10)
						numberToTrain = 10;
					if (availableSpace < 10) {
						numberToTrain = 1;
					}
					actionLog(culang.tabLabelAutoTrain, Cities.byID[cityId].name + ' - ' + culang.autoTrainWall +' ' + numberToTrain + ' ' + uW.fortcost['frt61'][0]);
					doDefTrain(cityId, 0, 61, numberToTrain);
				}
			}
		}
	},
	doAutoSpikes: function (cityNo) {
		var t = Tabs.AutoTrain;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city' + cityId;
		getWallInfo(cityId, wall);
		availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 3) {
			var food = parseInt(Seed.resources['city' + cityId].rec1[0] / 3600);
			var wood = parseInt(Seed.resources['city' + cityId].rec2[0] / 3600);
			var stone = parseInt(Seed.resources['city' + cityId].rec3[0] / 3600);
			var ore = parseInt(Seed.resources['city' + cityId].rec4[0] / 3600);
			availableSlots = 3 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerSpike = wall.Def62Time;
			if (secsPerSpike && availableSpace > 3 && availableSlots > 0) {
				if (availFood > 150 && availWood > 750 & availStone > 50) {
					var numberToTrain = 9999999999;
					if ((availFood / 150) < numberToTrain)
						numberToTrain = parseInt(availFood / 150);
					if ((availWood / 750) < numberToTrain)
						numberToTrain = parseInt(availWood / 750);
					if ((availStone / 50) < numberToTrain)
						numberToTrain = parseInt(availStone / 50);
					if (numberToTrain > 10)
						numberToTrain = 10;
					if (availableSpace < 30) {
						numberToTrain = 1;
					}
					actionLog(culang.tabLabelAutoTrain, Cities.byID[cityId].name + ' - ' + culang.autoTrainWall +' ' + numberToTrain + ' ' + uW.fortcost['frt62'][0]);
					doDefTrain(cityId, 0, 62, numberToTrain);
				}
			}
		}
	},
	doAutoCrossbows: function (cityNo) {
		var t = Tabs.AutoTrain;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city' + cityId;
		getWallInfo(cityId, wall);
		availableSpace = wall.wallSpace - wall.wallSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 2) {
			var food = parseInt(Seed.resources['city' + cityId].rec1[0] / 3600);
			var wood = parseInt(Seed.resources['city' + cityId].rec2[0] / 3600);
			var stone = parseInt(Seed.resources['city' + cityId].rec3[0] / 3600);
			var ore = parseInt(Seed.resources['city' + cityId].rec4[0] / 3600);
			availableSlots = 2 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerXbow = wall.Def53Time;
			if (secsPerXbow && availableSpace > 2 && availableSlots > 0) {
				if (availFood > 250 && availWood > 2000 & availStone > 750 & availOre > 500) {
					var numberToTrain = 9999999999;
					if ((availFood / 250) < numberToTrain)
						numberToTrain = parseInt(availFood / 250);
					if ((availWood / 2000) < numberToTrain)
						numberToTrain = parseInt(availWood / 2000);
					if ((availStone / 750) < numberToTrain)
						numberToTrain = parseInt(availStone / 750);
					if ((availOre / 500) < numberToTrain)
						numberToTrain = parseInt(availOre / 500);
					if (numberToTrain > 10)
						numberToTrain = 10;
					if (availableSpace < 20) {
						numberToTrain = 1;
					}
					actionLog(culang.tabLabelAutoTrain, Cities.byID[cityId].name + ' - ' + culang.autoTrainWall +' ' + numberToTrain + ' ' + uW.fortcost['frt53'][0]);
					doDefTrain(cityId, 0, 53, numberToTrain);
				}
			}
		}
	},
	doAutoTrebu: function (cityNo) {
		var t = Tabs.AutoTrain;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city' + cityId;
		getWallInfo(cityId, wall);
		availableSpace = wall.wallSpace - wall.wallSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 2) {
			var food = parseInt(Seed.resources['city' + cityId].rec1[0] / 3600);
			var wood = parseInt(Seed.resources['city' + cityId].rec2[0] / 3600);
			var stone = parseInt(Seed.resources['city' + cityId].rec3[0] / 3600);
			var ore = parseInt(Seed.resources['city' + cityId].rec4[0] / 3600);
			availableSlots = 2 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerTrebu = wall.Def55Time;
			if (secsPerTrebu && availableSpace > 4 && availableSlots > 0) {
				if (availFood > 500 && availWood > 3500 & availStone > 1800 & availOre > 1200) {
					var numberToTrain = 9999999999;
					if ((availFood / 500) < numberToTrain)
						numberToTrain = parseInt(availFood / 500);
					if ((availWood / 3500) < numberToTrain)
						numberToTrain = parseInt(availWood / 3500);
					if ((availStone / 1800) < numberToTrain)
						numberToTrain = parseInt(availStone / 1800);
					if ((availOre / 1200) < numberToTrain)
						numberToTrain = parseInt(availOre / 1200);
					if (numberToTrain > 10)
						numberToTrain = 10;
					if (availableSpace < 40) {
						numberToTrain = 1;
					}
					actionLog(culang.tabLabelAutoTrain, Cities.byID[cityId].name + ' - ' + culang.autoTrainWall +' ' + numberToTrain + ' ' + uW.fortcost['frt55'][0]);
					doDefTrain(cityId, 0, 55, numberToTrain);
				}
			}
		}
	},
	unitemax: function (currentcityid, e, numcity) {
		var t = Tabs.AutoTrain;
		var gumble = TrainOptions.listboost[currentcityid];
		var mult = 1;
		if (gumble == 0) mult = 1;
		if (gumble == 1) mult = 2;
		if (gumble == 2) mult = 4;
		var b = new Array();
		var a = new Array();
		for (var d = 1; d < 5; d++) {
			b.push((parseInt(uW.unitcost["unt" + e][d]) * 3600) * mult);
			a.push(parseInt(uW.seed.resources["city" + currentcityid]["rec" + d][0]))
		}
		b.push((parseInt(uW.unitcost["unt" + e][5])) * mult);
		a.push(parseInt(uW.seed.citystats["city" + currentcityid].gold[0]));
		b.push((parseInt(uW.unitcost["unt" + e][6])));
		if (!TrainOptions.listlabour[currentcityid]) {
			a.push(parseInt(uW.seed.citystats["city" + currentcityid].pop[0]) - parseInt(uW.seed.citystats["city" + currentcityid].pop[3]));
		} else {
			a.push(parseInt(uW.seed.citystats["city" + currentcityid].pop[0]) - parseInt(uW.seed.citystats["city" + currentcityid].pop[3]) + parseInt((parseInt(uW.seed.citystats["city" + currentcityid].pop[3]) * (TrainOptions.Workers[numcity] / 100))));
		}
		var c = a[0] / b[0];
		for (var d = 1; d < b.length; d++) {
			if (parseInt(b[d]) != 0) {
				c = Math.min(c, a[d] / b[d])
			}
		}
		if (c < 0) c = 0
		return parseInt(c) || 0
	},
	hide: function () {
		var t = Tabs.AutoTrain;
		t.saveOptionsAutoF();
	},
	show: function () {
		var t = Tabs.AutoTrain;
		if (TrainOptions.throneSet == undefined) TrainOptions.throneSet = 1;
		uW.Ks_AF_TU_Change = t.AF_TU_Change;
		m = "<DIV class=pdxStat>" + culang.autoTrainHead + " - <input type=button value='?' id=boaideautoform class=buttonHelp></div>";
		m += '<div style=""><TABLE width=95% class=pdxTab border=0 align=center>\
	    <tr align=center valign=top><TD><B>' + culang.mainIntervall + '</b>: <input id=aFtimelauch type=text size=2 value="' + parseInt(TrainOptions.timelauch) + '"> ' + culang.mainMinutes + '</TD>';
		m += '<TD><INPUT id=autoMilicienstoggle type=submit value="' + culang.autoTrainMode + '"><select id=KsModeFA>';
		var r = 0;
		for (y in uW.unitcost) {
			r++
			if (r == 13 || r == 14 || r == 15 || r == 17) continue;
			m += "<option value='" + r + "'>" + uW.unitcost[y][0] + "</option>";
		}
		m += "</select></td>";
		//ThroneSet 
		m += "<td><input type=checkbox id=Ks_AF_throneCheck " + (TrainOptions.throneCheck ? 'CHECKED' : '') + "> " + culang.mainTrainOnlyThroneSet + " <SELECT id=Ks_AF_throneSet>"; //15.10.2012 Bommel
		for (i = 1; i <= Seed.throne.slotNum; i++) {
			m += '<option value="' + i + '">' + i + '</option>';
		}
		m += '</select></td>';
		if (TrainOptions.Running == false) {
			m += '<TD><INPUT id=pbAutoTrainState type=submit value="' + culang.buttonAutoTrain + ' = ' + culang.buttonOFF + '"></td>';
		} else {
			m += '<TD><INPUT id=pbAutoTrainState type=submit value="' + culang.buttonAutoTrain + ' = ' + culang.buttonON + '"></td>';
			// t.timer=setTimeout(t.Start,5000);
			saveTrainingOptions();
		}
		m += "</tr></table><div id='Ks_AF_Progression' style='max-height:100px; overflow:auto'></div>";
		m += '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'autoTrainOpt\').style.display=(document.getElementById(\'autoTrainOpt\').style.display== \'block\')?\'none\':\'block\';">' + culang.autoTrainHeadOptions + '</a></div>';
		m += '<DIV id="autoTrainOpt" style="display:none;">';
		m += '<table width=98% class=pdxTab border=0 align=left>\
	<tr><td>' + culang.autoTrainCalcWorkers + ' <select id=KsModeDiv><option value=25>25%</option><option value=50>50%</option><option value=75>75%</option><option value=90>90%</option><option value=100>100%</option></select> - <input type=button value="' + culang.autoTrainCalculate + '" id=Ks_AllCalculate></td></tr>';
		m += "<tr><td><input type=checkbox id=Ks_AF_CancelFirst> " + culang.autoTrainDelete + " </td><td><input type=button value='" + culang.autoTrainDeleteAll + "' id=Ks_AF_CancelAll></td></tr>\
	<tr><td><sup><span class='boldRed'><u>" + culang.mainImportant + "</u></span>:</sup> <span class='helpText'>" + culang.autoTrainWallBuildNote + "</span></td></tr></table>";
		m += '</div>';
		m += "<TABLE width=98% class=pdxTab border=0 align=center cellspacing=0 cellpadding=1 align=left>\
          <tr align=center><td align=center style='border-bottom:1px solid #141516;' colspan=2><b><u>" + culang.mainCastle + "</u></td>\
          <td align=center style='border-bottom:1px solid #141516;'><b><u>" + culang.autoTrainUnitType + "</u></td>\
          <td align=center style='border-bottom:1px solid #141516;'><b><u>" + culang.shortMin + "</u></td>\
          <td align=center style='border-bottom:1px solid #141516;'><b><u>" + culang.shortMax + "</u></td>\
          <td align=center style='border-bottom:1px solid #141516;' colspan=2><a id='Ks_WorkersCalc'><b>" + culang.autoTrainWorker + "</a></td>\
          <tD align=center style='border-bottom:1px solid #141516;'><b><u>" + culang.mainSpeedups + "</u></td></tr>";
		var city = 0;
		for (var c = 0; c < Cities.numCities; c++) {
			cityId = Cities.cities[c].id;
			var citynum = Seed.cities[c][0];
			city = c + 1;
			m += "<tr><td rowspan=4 width=10% align=left style='border-bottom:1px solid #141516;'><b>" + (c + 1) + "</b> : " + Cities.cities[c].name + "<br></td><td align=right rowspan=4 style='border-bottom:1px solid #141516;'>";
			if (TrainOptions.listactif && TrainOptions.listactif[cityId] == false) {
				m += "<input type=checkbox id='autoFCheck_" + cityId + "'>";
			} else {
				m += "<input checked type=checkbox id='autoFCheck_" + cityId + "'>";
			}
			m += "</td><TD><SELECT id='autoFType_" + cityId + "' onchange='Ks_AF_TU_Change(" + cityId + ",this.value);'>";
			var r = 0;
			for (y in uW.unitcost) {
				r++
				var faux = 0;
				var uc = uW.unitcost[y];
				if (r > 12 && r != 16) {
					continue;
				}
				if (Seed.cityData && Seed.cityData.city[cityId].isPrestigeCity) {} else {
					if (matTypeof(uc[8]) == 'object') {
						for (k in uc[8]) {
							var b = getCityBuilding(cityId, k.substr(1));
							if (b.maxLevel < uc[8][k][1]) {
								faux = 1;
								break;
							}
						}
					}
				}
				if (matTypeof(uc[9]) == 'object') {
					for (k in uc[9]) {
						if (parseInt(Seed.tech['tch' + k.substr(1)]) < uc[9][k][1]) {
							faux = 1;
							break;
						}
					}
				}
				if (faux == 0) {
					if (TrainOptions.list) {
						if (r == TrainOptions.list[cityId]) {
							m += "<option selected value='" + r + "'>" + uW.unitcost[y][0] + "</option>";
						} else {
							m += "<option value='" + r + "'>" + uW.unitcost[y][0] + "</option>";
						}
					} else {
						if (r == 2) {
							TrainOptions.list[cityId] = r;
							m += "<option selected value='" + r + "'>" + uW.unitcost[y][0] + "</option>";
						} else {
							m += "<option value='" + r + "'>" + uW.unitcost[y][0] + "</option>";
						}
					}
				}
			}
			if (TrainOptions.unitemax[Cities.cities[c].id] == undefined) TrainOptions.unitemax[Cities.cities[c].id] = 999999;
			if (TrainOptions.ascension[Cities.cities[c].id] == undefined) TrainOptions.ascension[Cities.cities[c].id] = false;
			if (isNaN(parseInt(TrainOptions.unitemin[cityId]))) TrainOptions.unitemin[cityId] = 0;
			if (TrainOptions.Keep[city] == undefined) TrainOptions.Keep[city] = {};
			m += "</select></td><td align=left><input type=text value='" + parseIntNan(TrainOptions.unitemin[cityId]) + "' id='aFunitemin_" + cityId + "' size=4></td><td align=left><input type=text value='" + parseIntNan(TrainOptions.unitemax[cityId]) + "' id='aFunitemax_" + cityId + "' size=5></td><td align=right>";
			if (TrainOptions.listlabour && TrainOptions.listlabour[cityId] == false) {
				m += "<input type=checkbox class=" + city + " id='autoFWorkers_" + cityId + "'>";
			} else {
				m += "<input checked class=" + city + " type=checkbox id='autoFWorkers_" + cityId + "'>";
			}
			m += "</td><td align=right>";
			m += '<SELECT class=' + city + ' id="workers' + city + '"><option value="0">0%</options>';
			m += '<option value="25">25%</options><option value="50">50%</options><option value="75">75%</options><option value="100">100%</options></select></td><td align=right>';
			m += "<select id='autoFboost_" + cityId + "'>";
			m += "<option value=0>" + culang.mainNormal + "</option><option value=1 " + (TrainOptions.listboost[cityId] == 1 ? 'SELECTED ' : '') + ">5-15%</option><option value=2 " + (TrainOptions.listboost[cityId] == 2 ? 'SELECTED ' : '') + ">10-25%</option></select>";
			m += '<br><select class=' + city + ' id="TrainSpeedItem_' + city + '"><option value=0><CENTER>-- ' + uW.g_js_strings.commonstr.items + ' --</center></option>\
 			<option value=36>' + uW.itemlist.i36.name + '</option>\
  			<option value=37>' + uW.itemlist.i37.name + '</option>\
			<option value=38>' + uW.itemlist.i38.name + '</option></select></td></tr>';
			if (Seed.cityData.city[citynum].prestigeInfo.blessings) {
				if (Seed.cityData.city[citynum].prestigeInfo.blessings.indexOf(11) != -1) {
					m += '<tr><td align=left><INPUT class=' + city + ' id=AsEnabled' + city + ' type=checkbox ' + (TrainOptions.AsEnabled[city] ? 'CHECKED' : '') + '> ' + uW.unitcost['unt13'][0] + ' </td><td><INPUT class=' + city + ' id=AsTroops' + city + ' type=text size=4 maxlength=6 value="' + TrainOptions.AsTroops[city] + '"></td><td><INPUT class=' + city + ' id=AsMaxTroops' + city + ' type=text size=5 maxlength=6 value="' + TrainOptions.AsMaxTroops[city] + '"></td><td></td><td></td><td></td></tr>';
				};
				if (Seed.cityData.city[citynum].prestigeInfo.blessings.indexOf(21) != -1) {
					m += '<tr><td align=left><INPUT class=' + city + ' id=AsEnabled' + city + ' type=checkbox ' + (TrainOptions.AsEnabled[city] ? 'CHECKED' : '') + '> ' + uW.unitcost['unt14'][0] + ' </td><td><INPUT class=' + city + ' id=AsTroops' + city + ' type=text size=4 maxlength=6 value="' + TrainOptions.AsTroops[city] + '"></td><td><INPUT class=' + city + ' id=AsMaxTroops' + city + ' type=text size=5 maxlength=6 value="' + TrainOptions.AsMaxTroops[city] + '"></td><td></td><td></td><td></td></tr>';
				};
				if (Seed.cityData.city[citynum].prestigeInfo.blessings.indexOf(31) != -1) {
					m += '<tr><td align=left><INPUT class=' + city + ' id=AsEnabled' + city + ' type=checkbox ' + (TrainOptions.AsEnabled[city] ? 'CHECKED' : '') + '> ' + uW.unitcost['unt15'][0] + ' </td><td><INPUT class=' + city + ' id=AsTroops' + city + ' type=text size=4 maxlength=6 value="' + TrainOptions.AsTroops[city] + '"></td><td><INPUT class=' + city + ' id=AsMaxTroops' + city + ' type=text size=5 maxlength=6 value="' + TrainOptions.AsMaxTroops[city] + '"></td><td></td><td></td><td></td></tr>';
				};
			} else {
				m += '<tr></tr>';
			}
			m += '<TR><td colspan=6><img width=23 src="' + IMGfood30 + '">&nbsp;';
			m += '<INPUT class=' + city + '  id="KeepFood' + city + '" type=text size=7 maxlength=8 value="' + parseIntNan(TrainOptions.Keep[city]['Food']) + '"\>&nbsp;';
			m += '<img width=23 src="' + IMGwood30 + '">&nbsp;';
			m += '<INPUT class=' + city + ' id="KeepWood' + city + '" type=text size=7 maxlength=8 value="' + parseIntNan(TrainOptions.Keep[city]['Wood']) + '"\>&nbsp;';
			m += '<img width=23 src="' + IMGstone30 + '">&nbsp;';
			m += '<INPUT class=' + city + '  id="KeepStone' + city + '" type=text size=7 maxlength=8 value="' + parseIntNan(TrainOptions.Keep[city]['Stone']) + '"\>&nbsp;';
			m += '<img width=23 src="' + IMGiron30 + '">&nbsp;';
			m += '<INPUT class=' + city + ' id="KeepOre' + city + '" type=text size=7 maxlength=8 value="' + parseIntNan(TrainOptions.Keep[city]['Ore']) + '"\>';
			m += "</td></tr>";
			m += "<TR><td colspan=8 style='border-bottom:1px solid #141516;'><b>" + culang.autoTrainWallBuild + "</b> <INPUT class=" + city + " type=CHECKBOX id='chkDoTraps" + city + "' " + (TrainOptions.doTraps[city] ? ' CHECKED ' : '') + ">" + uW.fortcost.frt60[0] + "&nbsp;\
        	<INPUT class=" + city + " type=CHECKBOX id='chkDoCaltrops" + city + "' " + (TrainOptions.doCalrops[city] ? ' CHECKED ' : '') + ">" + uW.fortcost.frt61[0] + "&nbsp;\
        	<INPUT class=" + city + " type=CHECKBOX id='chkDoSpikes" + city + "' " + (TrainOptions.doSpikes[city] ? ' CHECKED ' : '') + ">" + uW.fortcost.frt62[0] + "&nbsp;\
        	<INPUT class=" + city + " type=CHECKBOX id='chkDoXbows" + city + "' " + (TrainOptions.doXbows[city] ? ' CHECKED ' : '') + ">" + uW.fortcost.frt53[0].substr(0, 9) + "&nbsp;\
       	<INPUT class=" + city + " type=CHECKBOX id='chkDoTrebu" + city + "' " + (TrainOptions.doTrebu[city] ? ' CHECKED ' : '') + ">" + uW.fortcost.frt55[0] + "</TD></TR>";
		}
		m += "</table></div><div>";
		t.cont.innerHTML = m;
		ById('Ks_AF_throneCheck')
			.addEventListener('click', function (e) {
				TrainOptions.throneCheck = e.target.checked;
				saveTrainingOptions();
			}, false);
		ById('Ks_AF_throneSet')
			.value = TrainOptions.throneSet;
		ById('Ks_AF_throneSet')
			.addEventListener('change', function (e) {
				TrainOptions.throneSet = this.value;
				saveTrainingOptions();
			}, false);
		ById('boaideautoform')
			.addEventListener('click', function () {
				window.open(homePage + " ");
			}, false);
		for (i = 0; i < Seed.cities.length; i++) {
			city = i + 1;
			cityId = Cities.cities[i].id;
			ById('workers' + city).value = TrainOptions.Workers[city];
			ById('TrainSpeedItem_' + city).value = TrainOptions.Item[city];
			//??ById('autoFboost_'+cityId).value = TrainOptions.Item[city];
		}
		ById('KsModeDiv')
			.value = TrainOptions.UnitMixValue;
		ById('KsModeDiv')
			.addEventListener('change', function (e) {
				TrainOptions.UnitMixValue = ById('KsModeDiv').value;
				for (var c = 0; c < Cities.numCities; c++) {
					cityId = Cities.cities[c].id;
					t.AF_TU_Change(cityId, ById("autoFType_" + cityId).value);
				}
			}, false);
		ById('Ks_WorkersCalc').addEventListener('click', function () {
				t.workers();
			}, false);
		ById('Ks_AllCalculate').addEventListener('click', function () {
				for (var c = 0; c < Cities.numCities; c++) {
					cityId = Cities.cities[c].id;
					t.AF_TU_Change(cityId, ById("autoFType_" + cityId).value);
				}
			}, false);
		ById('pbAutoTrainState').addEventListener('click', function () {
				t.toggleAutoTrainState(this)
			}, false);
		ById('autoMilicienstoggle').addEventListener('click', function () {
				t.milicien()
			}, false);
		ById('Ks_AF_CancelAll').addEventListener('click', function () {
				t.AF_CancelAll()
			}, false);
		t.dispStatus = ById('Ks_AF_Progression');
		var k = 0;
		window.addEventListener('unload', t.onUnload, false);
		for (var c = 0; c < Cities.numCities; c++) {
			k = c + 1;
			cityID = Cities.cities[c].id;
			ById('aFunitemin_' + cityID).addEventListener('change', function () {
					t.saveOptionsAutoF();
				}, false);
			ById('aFunitemax_' + cityID).addEventListener('change', function () {
					t.saveOptionsAutoF();
				}, false);
			if (ById('AsEnabled' + k)) {
				ById('AsEnabled' + k).checked = TrainOptions.AsEnabled[k];
				ById('AsTroops' + k).value = parseIntNan(TrainOptions.AsTroops[k]);
				ById('AsMaxTroops' + k).value = parseIntNan(TrainOptions.AsMaxTroops[k]);
				if (ById('AsMaxTroops' + k).value < ById('AsTroops' + k).value) {
					ById('AsMaxTroops' + k).value = ById('AsTroops' + k).value;
					TrainOptions.AsMaxTroops[k] = ById('AsTroops' + k)
						.value;
					saveTrainingOptions();
				}
				ById('AsEnabled' + k)
					.addEventListener('change', function (e) {
						TrainOptions.AsEnabled[e.target['className']] = e.target.checked;
						saveTrainingOptions();
					}, false);
				ById('AsTroops' + k)
					.addEventListener('change', function (e) {
						if (isNaN(e.target.value)) e.target.value = 0;
						TrainOptions.AsTroops[e.target['className']] = e.target.value;
						saveTrainingOptions();
					}, false);
				ById('AsMaxTroops' + k)
					.addEventListener('change', function (e) {
						if (isNaN(e.target.value)) e.target.value = 0;
						if (TrainOptions.AsTroops[e.target['className']] > e.target.value) e.target.value = TrainOptions.AsTroops[e.target['className']];
						TrainOptions.AsMaxTroops[e.target['className']] = e.target.value;
						saveTrainingOptions();
					}, false);
			}
			ById('autoFWorkers_' + cityID)
				.addEventListener('click', function (e) {
					cityId = Cities.cities[(e.target['className'] - 1)].id;
					TrainOptions.listlabour[cityId] = ById('autoFWorkers_' + cityId)
						.checked;
					t.AF_TU_Change(cityId, ById("autoFType_" + cityId)
						.value);
				}, false);
			ById('workers' + k)
				.addEventListener('change', function (e) {
					TrainOptions.Workers[e.target['className']] = e.target.value;
					cityId = Cities.cities[(e.target['className'] - 1)].id;
					t.AF_TU_Change(cityId, ById("autoFType_" + cityId)
						.value);
				}, false);
			ById('TrainSpeedItem_' + k)
				.addEventListener('change', function (e) {
					TrainOptions.Item[e.target['className']] = e.target.value;
					saveTrainingOptions();
				}, false);
			ById('chkDoTraps' + k)
				.addEventListener('click', function (e) {
					TrainOptions.doTraps[e.target['className']] = e.target.checked;
					saveTrainingOptions();
				}, false);
			ById('chkDoCaltrops' + k)
				.addEventListener('click', function (e) {
					TrainOptions.doCalrops[e.target['className']] = e.target.checked;
					saveTrainingOptions();
				}, false);
			ById('chkDoSpikes' + k)
				.addEventListener('click', function (e) {
					TrainOptions.doSpikes[e.target['className']] = e.target.checked;
					saveTrainingOptions();
				}, false);
			ById('chkDoXbows' + k)
				.addEventListener('click', function (e) {
					TrainOptions.doXbows[e.target['className']] = e.target.checked;
					saveTrainingOptions();
				}, false);
			ById('chkDoTrebu' + k)
				.addEventListener('click', function (e) {
					TrainOptions.doTrebu[e.target['className']] = e.target.checked;
					saveTrainingOptions();
				}, false);
			ById('KeepFood' + k)
				.addEventListener('change', function (e) {
					if (isNaN(e.target.value)) e.target.value = 0;
					TrainOptions.Keep[e.target['className']]['Food'] = e.target.value;
					saveTrainingOptions();
				}, false);
			ById('KeepWood' + k)
				.addEventListener('change', function (e) {
					if (isNaN(e.target.value)) e.target.value = 0;
					TrainOptions.Keep[e.target['className']]['Wood'] = e.target.value;
					saveTrainingOptions();
				}, false);
			ById('KeepStone' + k)
				.addEventListener('change', function (e) {
					if (isNaN(e.target.value)) e.target.value = 0;
					TrainOptions.Keep[e.target['className']]['Stone'] = e.target.value;
					saveTrainingOptions();
				}, false);
			ById('KeepOre' + k)
				.addEventListener('change', function (e) {
					if (isNaN(e.target.value)) e.target.value = 0;
					TrainOptions.Keep[e.target['className']]['Ore'] = e.target.value;
					saveTrainingOptions();
				}, false);
		}
	},
	unload: function () {
		var t = Tabs.AutoTrain;
		t.saveOptionsAutoF();
	},
	checkresources: function (cityId, city) {
		var t = Tabs.AutoTrain;
		var city = city + 1;
		t.food = parseInt((Seed.resources['city' + cityId].rec1[0] / 3600) - parseIntNan(TrainOptions['Keep'][city]['Food']));
		t.wood = parseInt((Seed.resources['city' + cityId].rec2[0] / 3600) - parseIntNan(TrainOptions['Keep'][city]['Wood']));
		t.stone = parseInt((Seed.resources['city' + cityId].rec3[0] / 3600) - parseIntNan(TrainOptions['Keep'][city]['Stone']));
		t.ore = parseInt((Seed.resources['city' + cityId].rec4[0] / 3600) - parseIntNan(TrainOptions['Keep'][city]['Ore']));
		if (t.food > 0 && t.wood > 0 && t.stone > 0 && t.ore > 0) {
			return true;
		}
		return false;
	},
	AF_TU_Change: function (cityId, unit) {
		var t = Tabs.AutoTrain;
		var coutenpop = uW.unitcost['unt' + unit][6];
		var numcity = Cities.byID[cityId].idx + 1;
		var X = Seed.citystats['city' + cityId]["pop"][1];
		var Y = uW.seed.citystats["city" + cityId].pop[3];
		var Q = coutenpop;
		var Z = 0;
		var M = ById("KsModeDiv")
			.value / 100;
		if (ById("autoFWorkers_" + cityId)
			.checked) {
			Z = ById('workers' + numcity)
				.value / 100;
			ById("aFunitemax_" + cityId)
				.value = parseIntNan(X / Q);
		} else {
			Z = 0;
			ById("aFunitemax_" + cityId)
				.value = parseIntNan((X - Y) / Q);
		}
		var Min = ((X - (Y * (1 - Z))) * M) / Q;
		if (Min < 0) Min = 0;
		ById("aFunitemin_" + cityId)
			.value = parseIntNan(Min);
		if (ById("aFunitemax_" + cityId)
			.value < 0) {
			ById("aFunitemax_" + cityId)
				.value = 0;
			ById("aFunitemin_" + cityId)
				.value = 0;
		}
		t.saveOptionsAutoF();
	},
	workers: function () {
		var t = Tabs.AutoTrain;
		for (var c = 0; c < Cities.numCities; c++) {
			if (ById('workers' + (c + 1))
				.value == "100")
				ById('workers' + (c + 1))
					.value = "25"
			else
				ById('workers' + (c + 1))
					.value = "100";
			TrainOptions.Workers[(c + 1)] = ById('workers' + (c + 1))
				.value;
			cityId = Cities.cities[c].id;
			t.AF_TU_Change(cityId, ById("autoFType_" + cityId)
				.value);
		}
		t.saveOptionsAutoF();
	},
	milicien: function () {
		var t = Tabs.AutoTrain;
		var typeunite = ById('KsModeFA')
			.value;
		ById('KsModeDiv')
			.value = "90";
		var coutenpop = uW.unitcost['unt' + typeunite][6];
		for (var c = 0; c < Cities.numCities; c++) {
			cityId = Cities.cities[c].id;
			ById("autoFWorkers_" + Cities.cities[c].id)
				.checked = true;
			ById("autoFCheck_" + Cities.cities[c].id)
				.checked = true;
			ById("autoFType_" + Cities.cities[c].id)
				.value = typeunite;
			t.AF_TU_Change(cityId, ById("autoFType_" + cityId)
				.value);
		}
		for (var c = 0; c < Cities.numCities; c++) {
			cityId = Cities.cities[c].id;
			t.AF_TU_Change(cityId, ById("autoFType_" + cityId)
				.value);
		}
		t.saveOptionsAutoF();
	},
	saveOptionsAutoF: function () {
		var t = Tabs.AutoTrain;
		if (parseIntNan(ById('aFtimelauch').value) < 3) ById('aFtimelauch').value = "3";
		TrainOptions.timelauch = ById('aFtimelauch').value;
		TrainOptions.UnitMixValue = ById('KsModeDiv').value;
		TrainOptions.list = {};
		TrainOptions.listactif = {};
		TrainOptions.DisX = {};
		TrainOptions.listlabour = {};
		TrainOptions.unitemin = {};
		TrainOptions.unitemax = {};
		TrainOptions.listboost = {};
		for (var c = 0; c < Cities.numCities; c++) {
			TrainOptions.list[Cities.cities[c].id] = ById('autoFType_' + Cities.cities[c].id).value;
			TrainOptions.listactif[Cities.cities[c].id] = ById('autoFCheck_' + Cities.cities[c].id).checked;
			TrainOptions.listlabour[Cities.cities[c].id] = ById('autoFWorkers_' + Cities.cities[c].id).checked;
			TrainOptions.unitemin[Cities.cities[c].id] = parseIntNan(ById('aFunitemin_' + Cities.cities[c].id).value);
			TrainOptions.unitemax[Cities.cities[c].id] = parseIntNan(ById('aFunitemax_' + Cities.cities[c].id).value);	
			TrainOptions.listboost[Cities.cities[c].id] = ById('autoFboost_' + Cities.cities[c].id).value;
			TrainOptions.Workers[(c + 1)] = ById('workers' + (c + 1)).value;
			TrainOptions.Item[(c + 1)] = ById('TrainSpeedItem_' + (c + 1)).value;
		}
		saveTrainingOptions();
	},
	toggleAutoTrainState: function (obj) {
		var t = Tabs.AutoTrain;
		obj = ById('pbAutoTrainState');
		if (TrainOptions.Running == true) {
			TrainOptions.Running = false;
			clearTimeout(t.timer);
			if (obj) obj.value = culang.buttonAutoTrain + " = " + culang.buttonOFF;
			saveTrainingOptions();
		} else {
			TrainOptions.Running = true;
			clearTimeout(t.timer);
			t.numcity = -1;
			t.timer = setTimeout(t.Start, 5000);
			if (obj) obj.value = culang.buttonAutoTrain + " = " + culang.buttonON;
			saveTrainingOptions();
		}
	},
	CancelActionall: function (numville, num, fintraitement) {
		var t = Tabs.AutoTrain;
		var first = 1;
		var cityId = Cities.cities[numville].id;
		var q = Seed.queue_unt['city' + cityId];
		var now = unixTime();
		start = q[num][2];
		end = q[num][3];
		actual = end - now;
		if (actual < 0) actual = 0;
		var param2 = cityId;
		var param3 = q[num][0];
		var param4 = q[num][1];
		var param5 = end;
		var param6 = start;
		var param7 = actual;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cityId = param2;
		params.requestType = "CANCEL_TRAINING";
		params.numtrptrn = param4;
		params.trnETA = param5;
		params.trnNeeded = param7;
		params.trnTmp = param6;
		params.typetrn = param3;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/cancelTraining.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				var t = Tabs.AutoTrain;
				if (rslt.ok) {
					uW.update_seed_ajax(true, function () {
						var k = 0;
						for (var j = 0; j < uW.seed.queue_unt["city" + param2].length; j++) {
							if (j > num) {
								uW.seed.queue_unt["city" + param2][j][2] = parseInt(rslt.dateTraining[k]["start"]);
								uW.seed.queue_unt["city" + param2][j][3] = parseInt(rslt.dateTraining[k]["end"]);
								k++;
							}
						}
						uW.seed.queue_unt["city" + param2].splice(num, 1);
						for (var i = 1; i < 5; i++) {
							var totalReturn = parseInt(uW.unitcost["unt" + param3][i]) * parseInt(param4) * 3600 / 2;
							uW.seed.resources["city" + param2]["rec" + i][0] = parseInt(uW.seed.resources["city" + param2]["rec" + i][0]) + totalReturn;
						}
					});
					t.crfil++;
					ById('Ks_AF_Progression')
						.innerHTML = "<b><i>" + culang.autoTrainDeleteNow + " " + t.crfil + " / " + t.nbfil + "</i></b>";
					var numnew = num - 1;
					if (numnew < fintraitement) {
						if (numville == Cities.numCities) {
							ById('Ks_AF_Progression')
								.innerHTML = "<font color=#880000><B>" + culang.autoTrainTournamentNote + "</b></font>";
							return;
						}
						numville++;
						var cityId = Cities.cities[numville].id;
						var q = Seed.queue_unt['city' + cityId];
						numnew = q.length - 1;
						if (q.length <= fintraitement) {
							ById('Ks_AF_Progression')
								.innerHTML = "<font color=#550000><B>" + culang.autoTrainErrorTryAgain + "</b></font>";
							return;
						}
						setTimeout(function () {
							t.CancelActionall(numville, numnew, fintraitement);
						}, (Math.random() * 100) + 100);
					} else {
						setTimeout(function () {
							t.CancelActionall(numville, numnew, fintraitement);
						}, (Math.random() * 100) + 100);
					}
				} else {
					ById('Ks_AF_Progression')
						.innerHTML = "<font color=#550000><B>" + culang.autoTrainErrorDeleteNotPossible + "</b></font>";
				}
			},
			onFailure: function (rslt) {
				var t = Tabs.AutoTrain;
				ById('Ks_AF_Progression')
					.innerHTML = "<font color=#550000><B>" + culang.autoTrainErrorDeleteNotPossible + "</b></font>";
			}
		});
	},
	AF_CancelAll: function () {
		var t = Tabs.AutoTrain;
		t.nbfil = 0;
		t.crfil = 0;
		var debutsup = 1;
		if (ById('Ks_AF_CancelFirst').checked) {
			var debutsup = 0;
		}
		for (i = 0; i < Cities.numCities; i++) {
			var cityId = Cities.cities[i].id;
			var q = Seed.queue_unt['city' + cityId];
			t.nbfil += q.length - debutsup;
		}
		for (i = 0; i < Cities.numCities; i++) {
			var cityId = Cities.cities[i].id;
			var q = Seed.queue_unt['city' + cityId];
			if (q.length > debutsup) {
				obj = ById('pbAutoTrainState');
				TrainOptions.Running = false;
				if (obj) obj.value = culang.buttonAutoTrain + " = " + culang.buttonOFF;
				saveTrainingOptions();
				t.CancelActionall(i, q.length - 1, debutsup);
				return false;
			}
		}
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Train.js">
//	
//	   KOC POWER - TABS TRAIN											        
//	


Tabs.Train = {
	tabOrder: TabOptions.toTrain,
	tabLabel: culang.tabLabelTrain,
	cont : null,
	timer : null,
	stats : {},
	selectedCity : {},
	sourceCity : {},
	destinationCity : {},

	show : function (){
		var t = Tabs.Train;
		t.displayCityStats();
		t.changeTroopSelect();
		t.changeDefSelect();

		t.timer = setTimeout (t.show, 4000);
	},

	hide : function (){
		var t = Tabs.Train;
		clearTimeout (t.timer);
	},
	init : function (div){
		var t = Tabs.Train;
		t.cont = div;
		uW.KsCancelTraining = t.cancelTrainingNow;
		uW.KsCancelDefense = t.cancelDefenseNow;
		s = "<DIV id=trainTopSelect >\
        <DIV class=pdxStat>"+culang.trainHead+"</div><div id=ptTrainStatus style='overflow-y:auto; max-height:70px; text-align:center;'></div><DIV class=pdxEntry>\
        <DIV style='text-align:center;'><b>"+culang.mainCastle+"</b>: &nbsp; <span id=ptspeedcity></span></div>\
        <TABLE class=pdxTab width=100%><TR valign=top><TD width=50%>\
        <TABLE align=center><TR><TD align=right>"+culang.mainTroops+": </td><TD colspan=2>\
        <SELECT id=ptttType>";
			for (r=1; r<17; r++){
				if (r==2) {
					s+= "<option selected value='"+r+"'>"+uW.unitcost['unt'+r][0]+"</option>";
				} else {
					s+= "<option value='"+r+"'>"+uW.unitcost['unt'+r][0]+"</option>";
				}
			}
			if (Seed.items.i36){tutel1=Seed.items.i36}else{tutel1=0};
			if (Seed.items.i37){tutel2=Seed.items.i37}else{tutel2=0};
			if (Seed.items.i38){tutel3=Seed.items.i38}else{tutel3=0};
			if (Seed.items.i26){siege1=Seed.items.i26}else{siege1=0};
			s+= " </select> <br> ("+culang.shortMax+" <span id=ptttSpMax></span>)</td></tr>\
        <TR><TD align=right>"+culang.trainEachSlot+" </td><TD><INPUT id='ptttInpPS' size=5 type='text' value='0'\></td>\
          <TD><INPUT id='ptttButMaxPS' type=submit value='max'\> &nbsp; ("+culang.shortMax+" <span id=ptttSpMaxPS>0</span>)</td></tr>\
        <TR><TD align=right>"+culang.trainSlots+"</td><TD><INPUT id='ptttInpSlots' size=2 type='text' value='1'\></td>\
          <TD width=75%><INPUT id='ptttButMaxSlots' type=submit value='max'\> &nbsp; ("+culang.shortMax+" <span id=ptttSpMaxSlots>1</span>)</td></tr>\
        <TR><TD align=right valign=top>"+culang.autoTrainWorker+": </td><TD colspan=2><INPUT type=CHECKBOX id=chkPop"+ (Options.maxIdlePop?' CHECKED ':'') +">\
        "+culang.mainSpeedups+": <SELECT id=KsGamble>\
        <option value='0'>"+culang.mainNormal+"</option>\
        <option value='1'>5% - 15%</option>\
        <option value='2'>10% - 25%</option>\
        </select>\
        <br><SELECT id=tutelage>\
		<option value='0'><CENTER>-- "+culang.mainSpeedups+" --</center></option>\
		<option value='36'>"+ uW.itemlist.i36.name+" ("+tutel1+")</option>\
        <option value='37'>"+ uW.itemlist.i37.name+" ("+tutel2+")</option>\
        <option value='38'>"+ uW.itemlist.i38.name+" ("+tutel3+")</option>\
		</select>\
		</td></tr>\
        <TR><TD colspan=3 align=center><DIV style='height:10px'></div><INPUT id='ptttButDo' type=submit value='"+culang.trainNowButton+"'\>\
        <br><span id='expectedTrainTime'>"+culang.trainEST+"</span></td></tr>\
				<tr><td colspan=3><hr><table><tr><td><img width=40 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/34001.jpg></td><td><b>"+uW.itemlist.i34001.name+"</b>: </td><td><span id=train_i340001>"+addCommas(Seed.items.i34001)+"<span></td></tr></table></td></tr>\
        </table></td><TD width=20></td><TD style='border-left:solid 2px;' width=50% align=center>\
        <TABLE align=center><TR><TD align=right>"+culang.trainDefense+" </td><TD colspan=2>\
      <SELECT id=pttdType>\
        <option value='53'>"+uW.fortcost.frt53[0]+"</option>\
        <option value='55'>"+uW.fortcost.frt55[0]+"</option>\
        <option value='60'>"+uW.fortcost.frt60[0]+"</option>\
        <option value='61'>"+uW.fortcost.frt61[0]+"</option>\
        <option value='62'>"+uW.fortcost.frt62[0]+"</option>\
      </select> <br> (<span id=pttdSpMax></span>)</td></tr>\
        <TR><TD align=right>"+culang.trainEachSlot+" </td><TD><INPUT id='pttdInpPS' size=5 type='text' value='0'\></td>\
          <TD><INPUT id='pttdButMaxPS' type=submit value='max'\> ("+culang.shortMax+" <span id=pttdSpMaxPS>0</span>)</td></tr>\
        <TR><TD align=right>"+culang.trainSlots+"</td><TD><INPUT id='pttdInpSlots' size=2 type='text' value='1'></td>\
          <TD width=75%><INPUT id='pttdButMaxSlots' type=submit value='max'\> ("+culang.shortMax+" <span id=pttdSpMaxSlots>1</span>)</td></tr>\
        <TR align=center><TD colspan=3><SPAN id=pttdSpace></span></td></tr>\
         <TR><TD colspan=3 align=center><DIV style='height:10px'>\
      <SELECT id=siege>\
      <option value='0'><CENTER>--- "+culang.mainSpeedups+" ---</center></option>\
      <option value='26'>"+ uW.itemlist.i26.name+" ("+siege1+")</option>\
      </select></div>\
      <BR><INPUT id='pttdButDo' type=submit value='"+culang.trainDefenseNowButton+"'\>\
      <br><span id='expectedDefenseTime'>"+culang.trainEST+"</span> </td></tr></table>\
        </td></tr></table></div></div>\
        <div style='max-height:"+(Options.HauteurBoite-240)+"px; overflow-y:auto'>\
        <TABLE width=100% class=pdxTab><TR><TD colspan=3><DIV id=divSTtop></div></td></tr>\
        <TR><TD width=70% style='padding-left:5px; padding-right:5px; vertical-align:top;'>\
				<DIV style='text-align:center'>\
				<div class=pdxStat><img title='"+culang.trainCancelAllNote+"' src='"+IMGdeleteButton+"' border=0 id=KsCancelAllTrain1> "+culang.trainTrainHead+" (<SPAN id=statTTtot1></span>)</b></span></div>\
				</div>\
				<DIV id=divSTleft1 style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000;resize:both; overflow: auto;min-width: 50px;width: 600px; min-height: 1px; max-height:200px; height:150px;'></div>\
				<div id=divST2><br>\
				<DIV style='text-align:center'>\
				<div class=pdxStat><img title='"+culang.trainCancelAllNote+"' src='"+IMGdeleteButton+"' border=0 id=KsCancelAllTrain2> <span id=spType></span>"+culang.trainTrainHead+" (<SPAN id=statTTtot2></span>)</b></span></div>\
				</div>\
				<DIV id=divSTleft2 style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000;resize:both; overflow: auto;min-width: 50px;width: 600px; min-height: 1px; max-height:60px; height:150px;'></div>\
				</td>\
          <TD width=30% style='padding-left:5px; padding-right:5px; vertical-align:top;'><DIV style='text-align:center'><div  class=pdxStat>"+culang.trainDefenseHead+" (<SPAN id=statDTtot></span>)</b></div></div><DIV id=divSTright style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000; resize:both; overflow: auto; min-width: 50px; min-height:1px;max-height:"+(Options.HauteurBoite-590)+"px;'></div></td></tr>\
        </div></div></div>";
			t.cont.innerHTML = s;
			t.TTselType = document.getElementById ('ptttType');
			t.TTselType.addEventListener ('change', t.changeTroopSelect, false);
			t.TTinpPerSlot = document.getElementById ('ptttInpPS');			
			t.TTspMax = document.getElementById ('ptttSpMax');
			t.KsGamble = document.getElementById ('KsGamble');
			t.TTspMaxPS = document.getElementById ('ptttSpMaxPS');
			t.TTspMaxSlots = document.getElementById ('ptttSpMaxSlots');
			t.TTbutMaxSlots = document.getElementById ('ptttButMaxSlots');
			t.TTbutMaxPerSlot = document.getElementById ('ptttButMaxPS');
			t.TTinpSlots = document.getElementById ('ptttInpSlots');
			t.TTbutDo = document.getElementById ('ptttButDo');
			t.TDspMax = document.getElementById ('pttdSpMax');
			t.TDspMaxPS = document.getElementById ('pttdSpMaxPS');
			t.TDspMaxSlots = document.getElementById ('pttdSpMaxSlots');
			t.TDbutMaxSlots = document.getElementById ('pttdButMaxSlots');
			t.TDbutMaxPerSlot = document.getElementById ('pttdButMaxPS');
			t.TDinpPerSlot = document.getElementById ('pttdInpPS');
			t.TDinpSlots = document.getElementById ('pttdInpSlots');
			t.TDselType = document.getElementById ('pttdType');
			t.TDbutDo = document.getElementById ('pttdButDo');
			t.TDspSpace = document.getElementById ('pttdSpace');
			t.divTrainStatus = document.getElementById ('ptTrainStatus');
			t.divST2 = document.getElementById ('divST2');
			t.spType = document.getElementById ('spType');
			t.train_i340001 = document.getElementById ('train_i340001');
			var dcp = new CdispCityPicker ('ptspeed', ById('ptspeedcity'), true, t.clickCitySelect, 0);
			t.TTinpSlots.addEventListener ('change', t.updateTopTroops, false);
			t.KsGamble.addEventListener ('change', t.changeTroopSelect, false);
			t.TTbutMaxPerSlot.addEventListener ('click', t.clickTroopMaxPS, false);
			t.TTbutMaxSlots.addEventListener ('click', t.clickTroopMaxSlots, false);
			t.TTbutDo.addEventListener ('click', t.clickTroopDo, false);
			t.TDinpSlots.addEventListener ('change', t.updateTopDef, false);
			t.TDselType.addEventListener ('change', t.changeDefSelect, false);
			t.TDbutMaxPerSlot.addEventListener ('click', t.clickDefMaxPS, false);
			t.TDbutMaxSlots.addEventListener ('click', t.clickDefMaxSlots, false);
			t.TDbutDo.addEventListener ('click', t.clickDefDo, false);
			document.getElementById ('KsCancelAllTrain1').addEventListener ('click', function() {t.CancelAllTraining(false);}, false);
			document.getElementById ('KsCancelAllTrain2').addEventListener ('click', function() {t.CancelAllTraining(true);}, false);
			document.getElementById ('chkPop').addEventListener ('change', t.clickCheckIdlePop, false);

	},

	/*******  TROOPS  ******/
	updateTopTroops : function (){
		var t = Tabs.Train;
		var slots = parseInt(t.TTinpSlots.value, 10);
		var id = t.TTselType.value;
		if (isNaN(slots) || slots<0)
			slots = 0;
		t.TTspMax.innerHTML = t.stats.MaxTrain;
		if (id <=12 || i == 16)
			t.TTspMaxSlots.innerHTML = t.stats.barracks1 - t.stats.queued1;
		else 
			t.TTspMaxSlots.innerHTML = t.stats.barracks2 - t.stats.queued2;
			
		if (slots<1 || 
				(t.stats.barracks1-t.stats.queued1 < 1 && (id <=12 || id == 16)) || 
				(t.stats.barracks2-t.stats.queued2 < 1 && (id >12 && id <16)))
			t.TTspMaxPS.innerHTML = 0;
		else
			t.TTspMaxPS.innerHTML = parseInt(t.stats.MaxTrain / slots);
			
	},


	clickTroopMaxPS : function (){
		var t = Tabs.Train;
		var slots = parseInt(t.TTinpSlots.value, 10);
		var id = t.TTselType.value;
		if (slots<1 || 
				(t.stats.barracks1-t.stats.queued1 < 1 && (id <=12 || id == 16)) || 
				(t.stats.barracks2-t.stats.queued2 < 1 && (id >12 && id <16)))
			t.TTinpPerSlot.value = 0;
		else
			t.TTinpPerSlot.value = parseInt(t.stats.MaxTrain / slots);
	},

	clickTroopMaxSlots : function (){
		var t = Tabs.Train;
		var id = t.TTselType.value;
		if (id <=12 || id==16)
			t.TTinpSlots.value = t.stats.barracks1 - t.stats.queued1;
		else 
			t.TTinpSlots.value = t.stats.barracks2 - t.stats.queued2;
	},

	clickCitySelect : function (city){
		var t = Tabs.Train;
		t.selectedCity = city;
		t.lastQueString1 = null;
		t.lastQueString2 = null;
		t.lastDQueString = null;
		t.displayCityStats ();
		t.changeTroopSelect();
		t.changeDefSelect();
	},

	clickCheckIdlePop : function (){
		var t = Tabs.Train;
		if (document.getElementById ('chkPop').checked)
			Options.maxIdlePop = true;
		else
			Options.maxIdlePop = false;
		saveOptions ();
		t.displayCityStats ();
		t.changeTroopSelect ();
	},
	
	limitingFactor : null,
	
	changeTroopSelect : function (){
		var t = Tabs.Train;
		var cityId = t.selectedCity.id;
		var id = t.TTselType.value;
		t.lastTroopSelect = id;
		t.limitingFactor = null;
		var uc = uW.unitcost['unt'+id];
		var a=1
		var gumble= t.KsGamble.value;
		if (gumble==0) a=1;
		if (gumble==1) a=2;
		if (gumble==2) a=4;
		var max = 9999999999;
		if ( (t.stats.food / (uc[1]*a)) < max){
			max = t.stats.food / (uc[1]*a);
			t.limitingFactor = 'food';
		}
		if ( (t.stats.wood / (uc[2]*a)) < max){
			max = t.stats.wood / (uc[2]*a);
			t.limitingFactor = 'wood';
		}
		if ( (t.stats.stone / (uc[3]*a)) < max){
			max = t.stats.stone / (uc[3]*a);
			t.limitingFactor = 'stone';
		}
		if ( (t.stats.ore / (uc[4]*a)) < max){
			max = t.stats.ore / (uc[4]*a);
			t.limitingFactor = 'ore';
		}
		if ( (t.stats.idlePop / uc[6]) < max){
			max = t.stats.idlePop / (uc[6]);
			t.limitingFactor = 'pop';
		}
		//Eibenzweig
		if (id == 16 && parseInt(Seed.items.i34001) < max) {
			max = parseInt(Seed.items.i34001);
			t.limitingFactor = 'item';
		}
		t.stats.MaxTrain = parseInt (max);
		if (t.stats.MaxTrain < 0)
			t.stats.MaxTrain = 0;
		if (matTypeof(uc[8]) == 'object'){
			for (k in uc[8]){
				var b = getCityBuilding (cityId, k.substr(1));
				if (b.maxLevel < uc[8][k][1]){
					t.stats.MaxTrain = 0;
					t.limitingFactor = null;
					break;
				}
			}
		}
		if (matTypeof(uc[9]) == 'object'){
			for (k in uc[9]){
				if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
					t.stats.MaxTrain = 0;
					t.limitingFactor = null;
					break;
				}
			}
		}
		t.updateTopTroops();

	},

	clickTroopDo : function (){
		var t = Tabs.Train;

		var cityId = t.selectedCity.id;
		try {
		uW.citysel_click(ById('citysel_'+ (t.selectedCity.idx+1)+''));
		} catch (ex) {}
		var unitId = t.TTselType.value;
		var perSlot = parseInt(t.TTinpPerSlot.value, 10);
		var numSlots = parseInt(t.TTinpSlots.value, 10);

		t.displayCityStats ();
	
		if (perSlot<1){
			t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainNoSlotsNote+'</font>';
			return;
		}
		if (perSlot*numSlots > t.stats.MaxTrain){
			t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainTroopAmountNote+' '+ t.stats.MaxTrain +' '+culang.trainTroopAmountNote2+'</font>';
			return;
		}
		if (numSlots<1 || numSlots>t.stats.barracks - t.stats.queued){
			t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainWrongSlotsNote+'</font>';
			return;
		}

		var tut = document.getElementById ('tutelage').value;
		var gam = t.KsGamble.value;
		t.setBusy(true);
		var que = [];
		for (var i=0; i<numSlots; i++)
			que.push (['T', unitId, parseInt (perSlot)]);
		t.divTrainStatus.innerHTML = '';
		t.doQueue (cityId, tut, gam, que);
	},


	/*******  DEF  ******/

	updateTopDef : function (){
		var t = Tabs.Train;
		var slots = parseInt(t.TDinpSlots.value, 10);
		if (isNaN(slots) || slots<0)
			slots = 0;
		t.TDspMax.innerHTML = ''+culang.shortMax+' '+ t.stats.MaxDefTrain +'&nbsp; '+culang.trainOwned+':'+ t.stats.defOwned;
		t.TDspMaxSlots.innerHTML = t.stats.wallLevel-t.stats.Dqueued;
		if (slots<1)
			t.TDspMaxPS.innerHTML = 0;
		else
			t.TDspMaxPS.innerHTML = parseInt(t.stats.MaxDefTrain / slots);

		t.TDspSpace.innerHTML = '<table border=1 cellspacing=0 width=100% bordercolor=black><tr><td>'+uW.g_js_strings.commonstr.level+'</td><td>'+culang.trainWallDefense+'</td><td>'+culang.trainFieldDefense+'</td></tr>\
       <tr><td><B>'+ t.stats.wallLevel +'</b></td><td>'+ (t.stats.wallSpaceUsed+t.stats.wallSpaceQueued)  +'/<B>'+ t.stats.wallSpace +'</b></td>\
        <td>'+ (t.stats.fieldSpaceUsed+t.stats.fieldSpaceQueued) +'/<B>'+ t.stats.fieldSpace +'</b></td></table>';
	},

	changeDefSelect : function (){
		var t = Tabs.Train;
		var cityId = t.selectedCity.id;
		var id = t.TDselType.value;
		t.lastDefSelect = id;
		t.stats.defOwned = parseInt(Seed.fortifications['city' + cityId]['fort'+id]);
		var uc = uW.fortcost['frt'+id];
		var max = 9999999999;
		if ( (t.stats.food / uc[1]) < max)
			max = t.stats.food / uc[1];
		if ( (t.stats.wood / uc[2]) < max)
			max = t.stats.wood / uc[2];
		if ( (t.stats.stone / uc[3]) < max)
			max = t.stats.stone / uc[3];
		if ( (t.stats.ore / uc[4]) < max)
			max = t.stats.ore / uc[4];
		if ( (t.stats.idlePop / uc[6]) < max)
			max = t.stats.idlePop / uc[6];
		t.stats.MaxDefTrain = parseInt (max);
		if (t.stats.MaxDefTrain < 0)
			t.stats.MaxDefTrain = 0;
		if (matTypeof(uc[8]) == 'object'){
			for (k in uc[8]){
				var b = getCityBuilding (cityId, k.substr(1));
				if (b.maxLevel < uc[8][k][1]){
					t.stats.MaxDefTrain = 0;
					break;
				}
			}
		}
		if (matTypeof(uc[9]) == 'object'){
			for (k in uc[9]){
				if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
					t.stats.MaxDefTrain = 0;
					break;
				}
			}
		}

		var spaceEach = parseInt(uW.fortstats["unt"+ id][5]);
		if (id<60)
			var spaceAvail = t.stats.wallSpace - t.stats.wallSpaceUsed - t.stats.wallSpaceQueued;
		else
			var spaceAvail = t.stats.fieldSpace - t.stats.fieldSpaceUsed - t.stats.fieldSpaceQueued;
		if ( t.stats.MaxDefTrain * spaceEach > spaceAvail)
			t.stats.MaxDefTrain = parseInt(spaceAvail / spaceEach);

		t.updateTopDef();
	},

	clickDefMaxPS : function (){
		var t = Tabs.Train;
		var slots = parseInt(t.TDinpSlots.value, 10);
		if (slots<1)
			t.TDinpPerSlot.value = 0;
		else
			t.TDinpPerSlot.value = parseInt(t.stats.MaxDefTrain / slots);
	},

	clickDefMaxSlots : function (){
		var t = Tabs.Train;
		t.TDinpSlots.value = t.stats.wallLevel-t.stats.Dqueued;
	},

	clickDefDo : function (){
		var t = Tabs.Train;
		var cityId = t.selectedCity.id;
		var unitId = t.TDselType.value;
		var perSlot = parseInt(t.TDinpPerSlot.value, 10);
		var numSlots = parseInt(t.TDinpSlots.value, 10);

		t.displayCityStats ();
		if (perSlot<1){
			t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainZeroTroopsNote+'</font>';
			return;
		}
		if (perSlot*numSlots > t.stats.MaxDefTrain){
			t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainDefAmountNote+' '+ t.stats.MaxDefTrain +' '+culang.trainDefAmountNote2+'</font>';
			return;
		}
		if (numSlots<1 || numSlots > t.stats.wallLevel-t.stats.Dqueued){
			t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainWrongSlotsNote+'</font>';
			return;
		}
		var siege = document.getElementById ('siege').value;
		t.setBusy(true);
		var que = [];
		for (var i=0; i<numSlots; i++)
			que.push (['T', unitId, parseInt (perSlot)]);
		t.divTrainStatus.innerHTML = '';
		t.doDefQueue (cityId, siege, que);
	},

	doDefQueue : function (cityId, siege, que, errMsg){
		var t = Tabs.Train;
		try {
			t.displayCityStats();
			if (errMsg){
				t.dispTrainStatus ('<font color=#550000><B>'+culang.mainError+': '+ errMsg +'</b></font><BR>');
				t.setBusy(false);
				return;
			}
			var cmd = que.shift();
			if (!cmd){
				t.dispTrainStatus ('<B>'+culang.trainDoDefQueue+'</b><BR>');
				t.setBusy(false);
				return;
			}
			if (cmd[0] == 'T'){
				t.dispTrainStatus (''+culang.trainDefStatus+' <span class="boldRed">'+ cmd[2] +'</span> '+  fortNamesShort[cmd[1]] +' '+culang.trainDefStatus2+'<BR>');
				doDefTrain ( cityId, siege, cmd[1], cmd[2],
					function(errMsg){
						setTimeout(function (){Tabs.Train.doDefQueue(cityId, siege, que, errMsg);}, (Math.random()*3500)+500);
					} );
			}
		} catch (err) {
			t.dispTrainStatus ('<font color=#550000>'+culang.mainError+': '+ err.message +'</font><BR>');
			t.setBusy(false);
		}
	},
	setBusy : function (tf){
		var t = Tabs.Train;
		t.TDbutDo.disabled = tf;
		t.TTbutDo.disabled = tf;
	},
	fixQueTimes : function (q){
		var now = unixTime();
		if (q[0][2] > now)
			q[0][2] = now;
		for (var i=0; i<q.length; i++){
			if (q[i+1]!=null && q[i+1][2]!=q[i][3])
				q[i][3] = q[i+1][2];
		}
	},
	displayCityStats : function (){
		var t = Tabs.Train;
		try {
		var cityId = t.selectedCity.id;
		t.train_i340001.innerHTML = addCommas(Seed.items.i34001);
		t.stats.food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
		t.stats.wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
		t.stats.stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
		t.stats.ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
		t.stats.gold = Seed.citystats['city'+cityId].gold[0];
		if (Options.maxIdlePop)
			t.stats.idlePop = parseInt(Seed.citystats['city'+cityId].pop[0]);
		else
			t.stats.idlePop = parseInt(Seed.citystats['city'+cityId].pop[0]) - parseInt(Seed.citystats['city'+cityId].pop[3]);
		t.stats.barracks1 = getCityBuilding (cityId, 13).count;
		var asc = false;
		var asct = 0;
		if (Seed.cityData.city[cityId].isPrestigeCity) {
			asc = true;
			asct = Seed.cityData.city[cityId].prestigeInfo.prestigeType;
		}
		if (asct == 1) { //Druid
			t.stats.barracks2 = getCityBuilding (cityId, 22).count;
			t.spType.innerHTML = culang.ascDruid;
		} else if (asct == 2) { //Fey
			t.stats.barracks2 = getCityBuilding (cityId, 24).count;
			t.spType.innerHTML = culang.ascFey;
		} else if (asct == 3) { //Briton 
			t.stats.barracks2 = getCityBuilding (cityId, 26).count;
			t.spType.innerHTML = culang.ascBriton;
		} else {
			//Normale Stadt
		}
		if (asc) {
			t.divST2.style.display = "block";
		} else {
			t.divST2.style.display = "none";
		}
		cost = uW.unitcost['unt'+t.TTselType.value];
		nbunit=t.TTinpPerSlot.value*t.TTinpSlots.value;
		var a=1;
		var gumble= t.KsGamble.value;
		if (gumble==0) a=1;
		if (gumble==1) a=2;
		if (gumble==2) a=4;
		consoFood = cost[1] * a * nbunit;
		styleFood="";stylePop="";styleWood="";styleOre="";styleStone="";
		if (consoFood>t.stats.food) styleFood='style="color:#E30;font-weight:bold;"';
		consoOre = cost[4] * a * nbunit;
		if (consoOre>t.stats.ore) styleOre='style="color:#E30;font-weight:bold;"';
		consoStone = cost[3] * a * nbunit;
		if (consoStone>t.stats.stone) styleStone='style="color:#E30;font-weight:bold;"';
		consoWood = cost[2] * a * nbunit;
		if (consoWood>t.stats.wood) styleWood='style="color:#E30;font-weight:bold;"';
		consoPop = cost[6] * nbunit;
		if (consoPop>t.stats.idlePop) stylePop='style="color:#E30;font-weight:bold;"';

		var m = '<DIV class=pdxStat2>'+culang.mainTroopAmount+'</div>';
		m += '<TABLE class=pdxTab width=100%><TR align=center>';
		for (var i = 1; i<17; i++) {
			m+='<TD width=5.8%><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg" title="'+uW.unitcost['unt'+i][0]+'"></td>';
		}
		m+= '</tr><TR align=center>';
		for (var i = 1; i<17; i++) {
			m+= '<TD>'+addCommas(parseIntNan(Seed.units['city'+cityId]['unt'+i]))+'</td>';
		}
		m+= '</tr></table>';
		m += '<DIV class=pdxStat2>'+culang.mainRessources+'</div>';
		m += '<TABLE class=pdxTab width=100%><TR align=center>\
		<td width=15%>&nbsp;</td><TD width=14%><B>'+uW.g_js_strings.commonstr.gold+'</b></td><TD width=15%><B>'+uW.g_js_strings.commonstr.food+'</b></td><TD width=14%><B>'+uW.g_js_strings.commonstr.wood+'</b></td><TD width=14%><B>'+uW.g_js_strings.commonstr.stone+'</b></td><TD width=14%><B>'+uW.g_js_strings.commonstr.ore+'</b></td><TD width=14%><B>'+uW.g_js_strings.showPopTooltip.idlepop+'</b></td></tr>\
		<TR align=center><td><b><u>'+culang.mainInventory+'</u></b></td><TD><SPAN id=ptttr_gold>'+ UniteKMG(t.stats.gold) +'</span></td><TD><SPAN id=ptttr_food>'+ UniteKMG(t.stats.food) +'</span></td>\
		<TD><SPAN id=ptttr_wood>'+ UniteKMG(t.stats.wood) +'</span></td><TD><SPAN id=ptttr_stone>'+ UniteKMG(t.stats.stone) +'</span></td><TD><SPAN id=ptttr_ore>'+ UniteKMG(t.stats.ore) +'</span></td>\
		<TD><SPAN id=ptttr_gold>'+ addCommasInt(t.stats.idlePop) +'</span></td></tr>\
		<tr align=center><td width=15%><span class="boldRed">'+culang.mainNeed+'</span></td><td>&nbsp;</td><td '+styleFood+'>'+UniteKMG(consoFood)+'</td><td '+styleWood+'>'+UniteKMG(consoWood)+'</td><td '+styleStone+'>'+UniteKMG(consoStone)+'</td><td '+styleOre+'>'+UniteKMG(consoOre)+'</td>\
		<TD '+stylePop+'>'+ addCommasInt(consoPop)+'</td></tr>\
		</table>';

		document.getElementById ('divSTtop').innerHTML = m;
		var e=parseInt((t.TDinpPerSlot.value*t.TDinpSlots.value),10);
		if (e>0) {
			d=t.TDselType.value;
			var a=WallsTrainTime(d,e,cityId);
			var reduction=0
			var tut = ById('siege').value;
			if (tut==26) reduction=parseInt(a*0.3);
			var reducStr=timestr(reduction,1);
			ById('expectedDefenseTime').innerHTML=culang.trainEST+" <b>" + timestr(a,1) +"</b>";
			if (reduction>0) {
				var totalred = a - reduction;
				ById('expectedDefenseTime').innerHTML=culang.trainEST+" <b>" + timestr(totalred,1) +"</b>";
				ById('expectedDefenseTime').title=culang.trainEST+" " + timestr(a,1) +" - "+culang.trainESTreduction+": " + reducStr + "";
			}
		}
		var e=parseInt(nbunit,10);
		var b=t.TTselType.value;
		var selunit = b;
		if (e>0) {
			var m = TroopTrainTime(b, e, cityId);
				
			var reduction=0
			var tut = document.getElementById ('tutelage').value;
			if (tut==36)
				reduction=parseInt(m*0.3,10);
			if (tut==37)
				reduction=parseInt(m*0.5,10);
			if (tut==38)
				reduction=parseInt(m*0.7,10);

			var reducStr=timestr(reduction,1);

			var aa=1;
			var now = unixTime();
			var estimfin = new Date();
			estimfin.setTime((now+m) * 1000);
			ById('expectedTrainTime').innerHTML=culang.trainEST+" <b>" + timestr(m,1) +"</b><br>"+culang.trainTimeExpected+" "+estimfin.toLocaleString()+"";
			var gumble= t.KsGamble.value;
			if (gumble==0) aa=1;
			if (gumble==1) aa=2;
			if (gumble==2) aa=4;
			if (aa>1 && reduction==0) {
				if (aa==2) {
					var r1=parseInt(m*0.05,10);
					var r2=parseInt(m*0.15,10);
					var n1 = m - r1;
					var n2 = m - r2;
				}
				if (aa==4) {
					var r1=parseInt(m*0.10,10);
					var r2=parseInt(m*0.25,10);
					var n1 = m - r1;
					var n2 = m - r2;
				}
				var now = unixTime();
				var estimfin1 = new Date();
				estimfin1.setTime((now+n2) * 1000);
				var estimfin2 = new Date();
				estimfin2.setTime((now+n1) * 1000);
				ById('expectedTrainTime').innerHTML=culang.trainEST+" "+culang.trainESToutput+" <b><font color=red>" + timestr(n2,1) +"</font> "+culang.trainESToutput2+" <font color=red>" + timestr(n1,1) +"</font></b><br>"+culang.trainTimeExpected+" "+culang.trainESToutput3+" "+estimfin1.toLocaleString()+"<br>"+culang.trainESToutput4+" "+estimfin2.toLocaleString()+"";
			}
			if (reduction>0 && aa==1) {
				var totalred = m - reduction;
				var now = unixTime();
				var estimfin = new Date();
				estimfin.setTime((now+totalred) * 1000);
				ById('expectedTrainTime').innerHTML=culang.trainEST+" <b><font color=red>" + timestr(totalred,1) +"</font></b><br>"+culang.trainTimeExpected+" "+estimfin.toLocaleString()+"";
				ById('expectedTrainTime').title=culang.trainEST+" " + timestr(m,1) +" - "+culang.trainESTreduction+": " + reducStr + "";
			}
			if (reduction>0 && aa>1) {
				var totalred = m - reduction;
				if (aa==2) {
					var r1=parseInt(totalred*0.05,10);
					var r2=parseInt(totalred*0.15,10);
					var n1 = totalred - r1;
					var n2 = totalred - r2;
				}
				if (aa==4) {
					var r1=parseInt(totalred*0.10,10);
					var r2=parseInt(totalred*0.25,10);
					var n1 = totalred - r1;
					var n2 = totalred - r2;
				}

				var now = unixTime();
				var estimfin1 = new Date();
				estimfin1.setTime((now+n2) * 1000);
				var estimfin2 = new Date();
				estimfin2.setTime((now+n1) * 1000);
				ById('expectedTrainTime').innerHTML=culang.trainEST+" <b>"+culang.trainESToutput+" <font color=red>" + timestr(n2,1) +"</font> "+culang.trainESToutput2+" <font color=red>" + timestr(n1,1) +"</font></b><br>"+culang.trainTimeExpected+" <u>"+culang.trainESToutput3+"</u>  "+estimfin1.toLocaleString()+"<br><u>"+culang.trainESToutput4+"</u> "+estimfin2.toLocaleString()+"";
			}
		}
		var totTime = 0;
		var q = Seed.queue_unt['city'+cityId];
		var c = Cities.byID[cityId].idx;
		t.stats.q1 = [];
		t.stats.q2 = [];
		t.stats.queued1 = 0;
		t.stats.queued2 = 0;
		for (var i=0; i< q.length; i++) {
			var qe = q[i];
			qe[8] = i;
			if (qe[7]) {
				t.stats.queued2++;
				t.stats.q2.push(qe);
			} else {
				t.stats.queued1++;
				t.stats.q1.push(qe);
			}
		}
		var qs1 = t.stats.q1.toString();
		var qs2 = t.stats.q2.toString();
		var now = unixTime();
		
		//Warteschlange 1
		if (t.stats.q1.length>0)
			totTime1 = t.stats.q1[t.stats.q1.length-1][3] - now;
		else 
			totTime1 = 0;
		if (qs1 == t.lastQueString1){
			if (t.stats.q1.length>0){
				var cur = t.stats.q1[0][3] - now;
				if (cur < 1)
					t.stats.q1.shift();
				if (document.getElementById ('ptttfq1')) document.getElementById ('ptttfq1').innerHTML = timestr(cur, true);
			}
		} else {
			t.lastQueString1 = qs1;
			t.stats.queued1 = 0;
			m = '<TABLE align=center class=pdxTab>';
			if (t.stats.q1.length>0 ){
				t.fixQueTimes (t.stats.q1);
				t.stats.queued1 = t.stats.q1.length;
				first = true;
				for (var i=0; i<t.stats.q1.length; i++){
					start = t.stats.q1[i][2];
					end = t.stats.q1[i][3];
					if (first)
						actual = end - now;
					else
						actual = end - lastEnd;
					if (actual < 0)
						actual = 0;
						
					param1=t.stats.q1[i][8]; // 
					param2=cityId; // id de la ville
					param3=t.stats.q1[i][0]; // Type de trouoe
					param4=t.stats.q1[i][1]; // Qte troupe
					param5=end; // debut
					param6=start; // fin
					param7=actual; // duree
					m += '<TR align=right><td width=35 align=center>'+(i+1)+'&nbsp;<a onclick="KsCancelTraining('+param1+','+param2+','+param3+','+param4+','+param5+','+param6+','+param7+');return false;" href="javascript:void(0);"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.trainDelete+'"></a></td><TD>'+ t.stats.q1[i][1] +' </td><TD align=left> '+ uW.unitcost['unt'+t.stats.q1[i][0]][0].replace(''+culang.mainRallyPoint+'','');
					if (first)
						m += '</td><TD>&nbsp;<img src="'+IMGwaiting+'" onclick=citysel_click(document.getElementById(\'citysel_'+ (c+1)+'\'));modal_speedup("trn",'+param3+','+param3+',"Training",'+param6+');return false;> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=ptttfq1>'+ timestr(actual, true) +'</span>)';
					else
						m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>';
					lastEnd = end;
					first = false;
				}
			}
			m += '</table>';
			document.getElementById ('divSTleft1').innerHTML = m;
		}
		m = t.stats.barracks1 +' '+culang.trainCasernes+'';
		if (t.stats.queued1 > 0)
			m += ', '+ t.stats.queued1 +' '+culang.mainSlots+'';
		if (totTime1 > 0)
			m += ', '+ uW.timestr(totTime1);
		document.getElementById ('statTTtot1').innerHTML = m;
		
		//Warteschlange 2
		if (t.stats.q2.length>0)
			totTime2 = t.stats.q2[t.stats.q2.length-1][3] - now;
		else 
			totTime2 = 0;
		if (qs2 == t.lastQueString2){
			if (t.stats.q2.length>0){
				var cur = t.stats.q2[0][3] - now;
				if (cur < 1)
					t.stats.q2.shift();
				if (document.getElementById ('ptttfq2')) document.getElementById ('ptttfq2').innerHTML = timestr(cur, true);
			}
		} else {
			t.lastQueString2 = qs2;
			t.stats.queued2 = 0;
			m = '<TABLE align=center class=pdxTab>';
			if (t.stats.q2.length>0 ){
				t.fixQueTimes (t.stats.q2);
				t.stats.queued2 = t.stats.q2.length;
				first = true;
				for (var i=0; i<t.stats.q2.length; i++){
					start = t.stats.q2[i][2];
					end = t.stats.q2[i][3];
					if (first)
						actual = end - now;
					else
						actual = end - lastEnd;
					if (actual < 0)
						actual = 0;
					param1=t.stats.q2[i][8]; // 
					param2=cityId; // id de la ville
					param3=t.stats.q2[i][0]; // Type de trouoe
					param4=t.stats.q2[i][1]; // Qte troupe
					param5=end; // debut
					param6=start; // fin
					param7=actual; // duree
					m += '<TR align=right><td width=35 align=center>'+(i+1)+'&nbsp;<a onclick="KsCancelTraining('+param1+','+param2+','+param3+','+param4+','+param5+','+param6+','+param7+');return false;" href="javascript:void(0);"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.trainDelete+'"></a></td><TD>'+ t.stats.q2[i][1] +' </td><TD align=left> '+ uW.unitcost['unt'+t.stats.q2[i][0]][0].replace(''+culang.mainRallyPoint+'','');
					if (first)
						m += '</td><TD>&nbsp;<img src="'+IMGwaiting+'" onclick=citysel_click(document.getElementById(\'citysel_'+ (c+1)+'\'));modal_speedup("trn",'+param3+','+param3+',"Training",'+param6+');return false;> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=ptttfq2>'+ timestr(actual, true) +'</span>)';
					else
						m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>';
					lastEnd = end;
					first = false;
				}
			} 
			m += '</table>';
			document.getElementById ('divSTleft2').innerHTML = m;
		}
		m = t.stats.barracks2 +' '+culang.trainCasernes+'';
		if (t.stats.queued2 > 0)
			m += ', '+ t.stats.queued2 +' '+culang.mainSlots+'';
		if (totTime2 > 0)
			m += ', '+ uW.timestr(totTime2);
		document.getElementById ('statTTtot2').innerHTML = m;
		
		
		getWallInfo (cityId, t.stats);
		var totTime = 0;
		var q = Seed.queue_fort['city'+cityId];
		var qs = q.toString();
		if (q!=null && q.length>0)
			totTime = q[q.length-1][3] - now;
		if ( qs == t.lastDQueString){
			if (q!=null && q.length>0){
				var cur = q[0][3] - now;
				if (cur < 1)
					q.shift();
				document.getElementById ('pttdfq').innerHTML = timestr(cur, true);
			}
		} else {
			t.lastDQueString = qs;
			t.stats.Dqueued = 0;
			t.stats.wallSpaceQueued = 0;
			t.stats.fieldSpaceQueued = 0;
			m = '<TABLE align=center class=pdxTab>';
			if (q!=null && q.length > 0 ){
				t.fixQueTimes (q);
				t.stats.Dqueued = q.length;
				first = true;
				for (i=0; i<q.length; i++){
					if (q[i][0] < 60)
						t.stats.wallSpaceQueued += parseInt(uW.fortstats["unt"+ q[i][0]][5]) * parseInt(q[i][1]);
					else
						t.stats.fieldSpaceQueued += parseInt(uW.fortstats["unt"+ q[i][0]][5]) * parseInt(q[i][1]);
					start = q[i][2];
					end = q[i][3];
					if (first)
						actual = end - now;
					else
						actual = end - lastEnd;
					if (actual < 0)
						actual = 0;
					q[i][7]=cityId;
					m += '<TR align=right><TD><a onclick="KsCancelDefense('+ q[i][0]+','+q[i][1]+','+q[i][2]+','+q[i][3]+','+q[i][5]+','+q[i][6]+','+q[i][7] +','+ i +');return false;" href="javascript:void(0);"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.trainDeleteDefenseNote+'"></a></td><TD>'+ q[i][1] +'</td><TD align=left> '+ fortNamesShort[q[i][0]];
					if (first)
						m += '</td><TD> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=pttdfq>'+ timestr(actual, true) +'</span>)';
					else
						m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>';
					lastEnd = end;
					first = false;
				}
			}
			m += '</table>';
			document.getElementById ('divSTright').innerHTML = m;
		}
		m = t.stats.Dqueued +' '+culang.mainSlots+'';
		if (totTime > 0)
			m += ', '+ uW.timestr(totTime);
		document.getElementById ('statDTtot').innerHTML = m;
		} catch (ex) {	
		alert('18824/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
	},
	dispTrainStatus : function (msg){
		var t = Tabs.Train;
		t.divTrainStatus.innerHTML = msg + t.divTrainStatus.innerHTML;
	},
	CancelActionall: function(cityId, num, fintraitement, type) {
		var t = Tabs.Train;
try {		
		var q = Seed.queue_unt['city'+cityId];
		var isPrestigeQueue = Seed.queue_unt["city"+cityId][num][7];
		if (type != isPrestigeQueue) {
			var numnew = num - 1;
			if (numnew<fintraitement) {
				t.dispTrainStatus ('<font color=#550000><B>'+culang.trainDeleteMoreTrain+'</b></font><BR>');
				document.getElementById ('KsCancelAllTrain1').style.display='inline';
				document.getElementById ('KsCancelAllTrain2').style.display='inline';
				t.displayCityStats();
			} else {
				setTimeout(function (){
					t.CancelActionall(cityId, numnew, fintraitement, type);
				}, (Math.random()*200)+150);
			}
		}
		var now = unixTime();
		start = q[num][2];
		end = q[num][3];
		if (first)
			actual = end - now;
		else
			actual = end - lastEnd;
		if (actual < 0)
			actual = 0;
		var param2=cityId; // id de la ville
		var param3=q[num][0]; // Type de trouoe
		var param4=q[num][1]; // Qte troupe
		var param5=end; // debut
		var param6=start; // fin
		var param7=actual; // duree
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cityId = param2;
		params.requestType ="CANCEL_TRAINING";
		params.numtrptrn = param4;
		params.trnETA= param5;
		params.trnNeeded = param7;
		params.trnTmp = param6;
		params.typetrn= param3;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/cancelTraining.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				var t = Tabs.Train;
				if (rslt.ok) {
					
						var k=0;
						var isPrestigeQueue = Seed.queue_unt["city"+param2][num][7];
						for(var j=0;j<Seed.queue_unt["city"+param2].length;j++){
							if(j>num && (Seed.queue_unt["city" + param2][j][7] === isPrestigeQueue)){
								Seed.queue_unt["city"+param2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
								Seed.queue_unt["city"+param2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
								k++;
							}
						}
						Seed.queue_unt["city"+param2].splice(num,1);
						for(var i=1;i<5;i++){
							var totalReturn=parseInt(uW.unitcost["unt"+param3][i])*parseInt(param4)*3600/2;
							Seed.resources["city"+param2]["rec"+i][0]=parseInt(Seed.resources["city"+param2]["rec"+i][0])+totalReturn;
						}
				
					
					var numnew = num - 1;
					if (numnew<fintraitement) {
						t.dispTrainStatus ('<font color=#550000><B>'+culang.trainDeleteMoreTrain+'</b></font><BR>');
						document.getElementById ('KsCancelAllTrain1').style.display='inline';
						document.getElementById ('KsCancelAllTrain2').style.display='inline';
						t.displayCityStats();
					} else {
						setTimeout(function (){
							t.CancelActionall(cityId, numnew, fintraitement, type);
						}, (Math.random()*200)+150);
					}

				} else {
					t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorDelete+"</b></font><BR>");
					t.displayCityStats();
					document.getElementById ('KsCancelAllTrain1').style.display='inline';
					document.getElementById ('KsCancelAllTrain2').style.display='inline';
				}
			},
			onFailure: function (rslt) {
				var t = Tabs.Train;
				t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+":  "+culang.trainErrorDelete+"</b></font><BR>");
				t.displayCityStats();
				document.getElementById ('KsCancelAllTrain1').style.display='inline';
				document.getElementById ('KsCancelAllTrain2').style.display='inline';
			}
		});
} catch (ex) {
						alert('18923/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
}
	},
	CancelAllTraining : function(type) {
		var t = Tabs.Train;
try {
		var cityId = t.selectedCity.id;
		var q = Seed.queue_unt['city'+cityId];
		t.stats.q1 = [];
		t.stats.q2 = [];
		t.stats.queued1 = 0;
		t.stats.queued2 = 0;
		for (var i=0; i< q.length; i++) {
			var qe = q[i];
			qe[8] = i;
			if (qe[7]) {
				t.stats.queued2++;
				t.stats.q2.push(qe);
			} else {
				t.stats.queued1++;
				t.stats.q1.push(qe);
			}
		}
		if (type) {
			var q = t.stats.q2;
		} else {
			var q = t.stats.q1;
		}
		if (q.length>0) {
			var b=prompt(""+culang.trainDeleteMore+" "+(q.length)+""+culang.trainDeleteMore2+"", 2);
			if (parseInt(b)<=q.length && parseInt(b)>0) {
				t.dispTrainStatus ('<font color=#550000><B>'+culang.trainDeleteNow+'</b></font><BR>');
				document.getElementById ('KsCancelAllTrain1').style.display='none';
				document.getElementById ('KsCancelAllTrain2').style.display='none';
				obj = ById('pbAutoTrainState');
				TrainOptions.Running = false;
				if (obj) obj.value = culang.buttonAutoTrain+" = "+culang.buttonOFF;
				saveTrainingOptions();
				t.CancelActionall(cityId, q[q.length-1][8], q[b-1][8], type);
			}
		}
} catch (ex) {
						alert('18965/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
}
	},
	cancelTrainingNow : function (p1,p2,p3,p4,p5,p6,p7) {
		var t = Tabs.Train;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cityId = p2;
		params.requestType ="CANCEL_TRAINING";
		params.numtrptrn = p4;
		params.trnETA= p5;
		params.trnNeeded = p7;
		params.trnTmp = p6;
		params.typetrn= p3

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/cancelTraining.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				var t = Tabs.Train;
				if (rslt.ok) {
					
						var k=0;
						var isPrestigeQueue = Seed.queue_unt["city"+p2][p1][7];
						for(var j=0;j<Seed.queue_unt["city"+p2].length;j++){
							if(j>p1 && (Seed.queue_unt["city" + p2][j][7] === isPrestigeQueue)){
								Seed.queue_unt["city"+p2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
								Seed.queue_unt["city"+p2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
								k++;
							}
						}
						Seed.queue_unt["city"+p2].splice(p1,1);
						for(var i=1;i<5;i++){
							var totalReturn=parseInt(uW.unitcost["unt"+p3][i])*parseInt(p4)*3600/2;
							Seed.resources["city"+p2]["rec"+i][0]=parseInt(Seed.resources["city"+p2]["rec"+i][0])+totalReturn;
						}

					t.dispTrainStatus ('<font color=#550000><B>'+culang.trainSuccessfullyDel+'</b></font><BR>');
					t.displayCityStats();
				} else {
					t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancelTrain+"</b></font><BR>");
					t.displayCityStats();
				}
			},
			onFailure: function (rslt) {
				var t = Tabs.Train;
				t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancelTrain+"</b></font><BR>");
				t.displayCityStats();
			}
		});
	},
	cancelDefenseNow : function (typefrt, numtrpfrt, frtTmp, frtETA, frtNeeded, frtid, cityId, queueId){
		var t = Tabs.Train;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pf =0;
		params.requestType = "CANCEL_FORTIFICATIONS";
		params.cityId = cityId;
		params.typefrt = typefrt;
		params.numtrpfrt =  numtrpfrt;
		params.frtETA = frtETA;
		params.frtTmp = frtTmp;
		params.frtNeeded = frtNeeded;
		params.frtid = frtid;
		new AjaxRequest(uW.g_ajaxpath + "ajax/cancelFortifications.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (message) {
				var rslt=eval("("+message.responseText+")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				var t = Tabs.Train;
				if (rslt.ok) {
					var k=0;
					for(var j=0;j<Seed.queue_fort["city"+cityId].length;j++){
						if(j>queueId){
							Seed.queue_fort["city"+cityId][j][2]=parseInt(rslt.dateFortifications[k]["start"]);
							Seed.queue_fort["city"+cityId][j][3]=parseInt(rslt.dateFortifications[k]["end"]);
							k++;
						}
					}
					Seed.queue_fort["city"+cityId].splice(queueId,1);
					for(var i=1;i<5;i++){
						var totalReturn=parseInt(uW.fortcost["frt"+typefrt][i])*parseInt(numtrpfrt)*3600/2;
						Seed.resources["city"+cityId]["rec"+i][0]=parseInt(Seed.resources["city"+cityId]["rec"+i][0])+totalReturn;
					}
					t.dispTrainStatus ('<font color=#550000><B>'+culang.trainSuccessfullyDelDefense+'</b></font><BR>');
					t.displayCityStats();
				} else {

					t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancel+"</b></font><BR>");
					t.displayCityStats();
				}

			},
			onFailure: function () {
				var t = Tabs.Train;
				t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancel+"</b></font><BR>");
				t.displayCityStats();
			},
		});
	},
	doQueue : function (cityId, tut, gam, que, errMsg){
		var t = Tabs.Train;
		try {
			t.displayCityStats();
			if (errMsg){
				t.dispTrainStatus ('<font color=#550000><B>'+culang.mainError+': '+ errMsg +'</b></font><BR>');
				t.setBusy(false);
				return;
			}
			var cmd = que.shift();
			if (!cmd){
				t.dispTrainStatus ('<B>'+culang.trainSuccessfully+'</b><BR>');
				t.setBusy(false);
				return;
			}
			if (cmd[0] == 'T'){
				t.dispTrainStatus ('<i> '+culang.trainStatus+' <span class="boldRed"> '+ cmd[2] +'</span> '+  uW.unitcost['unt'+cmd[1]][0] +' '+culang.trainStatus2+' '+ Cities.byID[cityId].name +' '+culang.trainStatus3+' </i><BR>'); // ('+ que.length +' slot(s) restant(s)) - NEED TO FIX
				doTrain (cityId, tut, gam, cmd[1], cmd[2],
					function(errMsg){
						setTimeout(function (){Tabs.Train.doQueue(cityId, tut, gam, que, errMsg);}, (Math.random()*1000)+1000 );
					}
				);
			}
		} catch (err) {
			t.dispTrainStatus ('<font color=#550000>'+culang.mainError+': '+ err.message +'</font><BR>');
			t.setBusy(false);
		}
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Build.js">
//	
//	   KOC POWER - TABS AUTOBUILD										        
//	


Tabs.build = { //TODO rename to Build
	tabOrder: TabOptions.toBuild,
	tabLabel: culang.tabLabelAutoBuild,
	myDiv: null,
	timer: null,
	buildTab: null,
	koc_buildslot: null,
	currentBuildMode: null,
	buildStates: [],
	loaded_bQ: [],
	lbQ: [],
	SpeedCity: 0,
	
	UseSpeedup: function() {
		var t = Tabs.build;
		try {
		var now = unixTime();
		//RefreshSeed aktiv?
		if (RefreshingSeed) return;
		
		//Baufunktion nicht aktiv?
		if (t.buildStates.running == false) {
			return;
		}
		//Sollten Stundenglaeser verwendet werden?
		if (Options.buildUseSpeedups == false) {
			return;
		}
		//Stadt durchzaehlen
		if (t.SpeedCity >= Cities.cities.length) t.SpeedCity = 0;
		var cityId = Cities.cities[t.SpeedCity].id;
		t.SpeedCity++;
		//Bauauftrag suchen
		var time = 0;
		var bid = 0;
		var qcon = Seed.queue_con["city" + cityId];
		if (matTypeof(qcon)=='array' && qcon.length > 0) {
			if (parseIntNan(qcon[0][4]) > now + 15) {
				time = 	parseIntNan(qcon[0][4]) - now;
				bid = qcon[0][2];
			}	else {
				//Stadt wechseln
				setTimeout(t.UseSpeedup, 250);
				return;
			}
		} else {
			//Stadt wechseln
			setTimeout(t.UseSpeedup, 250);
			return;
		}
		//Passende Sanduhr ermitteln
		var item = getSpeedup(time);
		
		//Keine passende Sanduhr
		if (item == 0) {
			//Stadt wechseln
			setTimeout(t.UseSpeedup, 250);
			return;
		}	
		//Speedup verwenden
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid = cityId;
		params.iid = item;
		params.bid = bid;
		params.apothecary = false;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/speedupConstruction.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					//Item aus Inventar entfernen
					Seed.items["i" + item] = parseInt(Seed.items["i" + item]) - 1;
					uW.ksoItems[item].subtract();
					//Suche des Bauauftrages
					var qloc = 0;		
					for (var i = 0; i < Seed.queue_con["city" + cityId].length; i++) {
						if (parseInt(Seed.queue_con["city" + cityId][i][2]) == parseInt(bid)) {
							qloc = i;
							break;
						}
					}
					//Zeit um Itemzeit reduzieren
					var timered = 0;
					var timeredarr = [60, 900, 3600, 9000, 28800, 54000, 86400, 216000, 0, 345600];			
					var utstart = parseInt(Seed.queue_con["city" + cityId][qloc][3]);
					var uteta = parseInt(Seed.queue_con["city" + cityId][qloc][4]);
					timered = timeredarr[parseInt(item) - 1];
					Seed.queue_con["city" + cityId][qloc][3] = utstart - timered;
					Seed.queue_con["city" + cityId][qloc][4] = uteta - timered;
					if (cityId == uW.currentcityid) uW.update_queue();
					//Logbucheintrag
					var rep = {
						'item' : uW.itemlist['i'+item].name,
						'city' : Cities.byID[cityId].name,
					};
					actionLog(culang.tabLabelAutoBuild,culang.buildUseSpeedupsOK.mreplace(rep));		
				} else {
					//Logbucheintrag
					var rep = {
						'item' : uW.itemlist['i'+item].name,
						'city' : Cities.byID[cityId].name,
					};
					actionLog(culang.tabLabelAutoBuild,culang.buildUseSpeedupsFail.mreplace(rep) + ' <span class="boldRed">('+rslt.error_code+') ' + rsltErrorCode(rslt) + '</span>');	
				}
			},
		});
		//naechste Stadt
		} catch (ex) {
			alert('19215/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
		setTimeout(t.UseSpeedup, 5000);
	},

	init: function(div){
		var t = Tabs.build;
		t.myDiv = div;
		t.koc_buildslot = uW.buildslot;
		t.currentBuildMode = "build";
		t.buildStates = {
			running: false,
			help: false,
		};
		t.readBuildStates();

		for (var i = 0; i < Cities.cities.length; i++) {
			t["bQ_" + Cities.cities[i].id] = JSON2.parse(GM_getValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, '[]'));
			if (typeof t["bQ_" + Cities.cities[i].id] == 'undefined' || (t["bQ_" + Cities.cities[i].id]) == "") {
				t["bQ_" + Cities.cities[i].id] = [];
			}

		}

		var m = '<DIV id=pbBuildDivF class=pdxStat>'+culang.buildHead+'</div><TABLE id=pbbuildfunctions width=100% height=0% class=pdxTab><TR>';
		if (t.buildStates.running == false) {
			m += '<TD title="'+culang.buildButtonNote+'"><INPUT id=pbBuildRunning type=submit value="'+culang.buildButton+' = '+culang.buttonOFF+'"></td>';

		} else {
			m += '<TD><INPUT id=pbBuildRunning type=submit value="'+culang.buildButton+' = '+culang.buttonON+'"></td>';

		}
		m += '<TD><INPUT id=pbBuildMode type=submit value="'+culang.buildMode+' = '+culang.buttonOFF+'"></td>';


		m += '<TD>'+culang.buildModeSelect+' <SELECT id="pbBuildType">\
				<OPTION value=build>'+culang.buildModeLevel+'</option>\
				<OPTION value=max>'+culang.buildModeMax+'</option>\
				<OPTION value=destruct>'+culang.buildModeDestroy+'</option>\
				<OPTION value=destructnow>'+culang.buildModeDestroyNow+'</option>\
				</select></td>';
	
		m += '<TD style="text-align: right;">'+culang.buildAskForHelp+'&nbsp;';
		m += '<SELECT id="pbHelpRequest">\
				<OPTION value=off>' + culang.pbHelpRequestOff + '</option>\
				<OPTION value=chat>' + culang.pbHelpRequestChat + '</option>\
				<OPTION value=chatfb>' + culang.pbHelpRequestChatFB + '</option>\
				<OPTION value=chatfb10>' + culang.pbHelpRequestChatFB10 + '</option>\
				<OPTION value=chatfb20>' + culang.pbHelpRequestChatFB20 + '</option>\
				<OPTION value=chatfb30>' + culang.pbHelpRequestChatFB30 + '</option>\
				<OPTION value=chatfb60>' + culang.pbHelpRequestChatFB60 + '</option>\
				</select></td>'; //17.10.2012 Bommel
		m += '<td><input id=pbBuildSpeed type=checkbox>&nbsp;'+culang.buildUseSpeedups+'</td>';		
		m += '</tr></table></div>';
		m += '<DIV id=pbBuildDivQ class=pdxStat>'+culang.buildShowBuildQue+'</div><TABLE id=pbbuildqueues width=100% height=0% class=ptentry><TR>';
		for (var i = 0; i < Cities.cities.length; i++) {
			m += '<TD colspan=2><CENTER><B>' + Cities.cities[i].name + '</b></center></td>';
		}
		m += '</tr><TR>';
		for (var i = 0; i < Cities.cities.length; i++) {
			m += '<TD colspan=2><CENTER><INPUT id=pbbuild_' + Cities.cities[i].id + ' type=submit value="'+culang.mainShow+'"></center></td>';
		}
		m += '</tr><TR>';
		for (var i = 0; i < Cities.cities.length; i++) {
			m += '<TD colspan=2><CENTER><INPUT id=pbCancelAll_' + Cities.cities[i].id + ' type=submit value="'+culang.mainDeleteAll+'"></center></td>';
		}
		m += '</tr><TR>';

		for (var i = 0; i < Cities.cities.length; i++) {
			m += '<TD><div title="'+culang.buildShortBuildQuesNote+'">'+culang.buildShortBuildQues+'</div></td><TD id=pbbuildcount_' + Cities.cities[i].id + '>' + t["bQ_" + Cities.cities[i].id].length + '</td>';
		}
		m += '</tr><TR>';
		for (var i = 0; i < Cities.cities.length; i++) {
			t['totalTime_' + Cities.cities[i].id] = 0;
			cbQ = t["bQ_" + Cities.cities[i].id];
			if (typeof cbQ != 'undefined') {
				for (var j = 0; j < cbQ.length; j++) {
					t['totalTime_' + Cities.cities[i].id] = parseInt(t['totalTime_' + Cities.cities[i].id]) + parseInt(cbQ[j].buildingTime);
				}
				timestring = timestr(t['totalTime_' + Cities.cities[i].id]);
			}
			m += '<TD><div title="'+culang.buildShortBuildTimeNote+'">'+culang.buildShortBuildTime+'</div></td><TD id=pbbuildtotal_' + Cities.cities[i].id + '>' + timestring + '</td>';
		}
		m += '</tr></table><SPAN class=boldRed id=pbbuildError></span>';
		t.myDiv.innerHTML = m;

		for (var i = 0; i < Cities.cities.length; i++) {
			var cityId = Cities.cities[i].id;
			var btnName = 'pbbuild_' + cityId;
			addQueueEventListener(cityId, btnName);
			var btn2Name = 'pbCancelAll_' + cityId;
			CancelAllEventListener(cityId, btn2Name);
			t.showBuildQueue(cityId, false);
		}

		setTimeout(function() { t.e_autoBuild(0);  }, 10000);
		setTimeout(t.UseSpeedup, 11000);
		
		ById('pbBuildType').addEventListener('change', function(){t.setBuildMode(this.value);}, false);
		ById('pbBuildRunning').addEventListener('click', function(){
			t.toggleBuildStateRunning(this);
		}, false);
		ById('pbBuildMode').addEventListener('click', function(){
			t.toggleStateMode(this);
		}, false);
		ById('pbHelpRequest').value = t.buildStates.help;
		ById('pbHelpRequest').addEventListener ('change', function (){
			t.buildStates.help = ById('pbHelpRequest').value;
			t.saveBuildStates();
		}, false);

		window.addEventListener('unload', t.onUnload, false);
	
		t.togOpt("pbBuildSpeed","buildUseSpeedups");
	
		function addQueueEventListener(cityId, name){
			ById(name).addEventListener('click', function(){
				t.showBuildQueue(cityId, true);
			}, false);
		}

		function CancelAllEventListener(cityId, name){
			ById(name).addEventListener('click', function(){
				t["bQ_" + cityId] = [];
				t['totalTime_' + cityId] = 0;
				ById('pbbuildcount_' + cityId).innerHTML = 0;
				ById('pbbuildtotal_' + cityId).innerHTML = timestr(0);
			}, false);
		}


	},
	togOpt : function (checkboxId, optionName, callOnChange){
		var t = Tabs.Options;
		var checkbox = ById(checkboxId);
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (callOnChange)
				callOnChange (this.checked);
		}
	},
	setBuildMode: function (type) {
		var t = Tabs.build;
		t.currentBuildMode = type;
	},
	e_autoBuild: function(cityIdT){
		var t = Tabs.build;
		var ilya=0;
		ById('pbbuildError').innerHTML = '';
		//RefreshSeed aktiv?
		if (RefreshingSeed) {
			setTimeout(function() { t.e_autoBuild(0);  }, 2000);
			return;
		}
		for (var i = 0; i < Cities.cities.length; i++) {
			var cityId = Cities.cities[i].id;
			ilya+=t["bQ_" + cityId].length;
		}
		if (ilya < 1) {
			t.toggleBuildStateRunning();
			return;
		}
		if (t.buildStates.running == true) {
			var now = unixTime();
			for (var i = 0; i < Cities.cities.length; i++) {
				var cityId = Cities.cities[i].id;
				var isBusy = false;
				var qcon = Seed.queue_con["city" + cityId];
				if (matTypeof(qcon)=='array' && qcon.length>0) {
					if (parseIntNan(qcon[0][4]) > now)
						isBusy = true;
					else
						qcon.shift();
				}
				if (isBusy) {
					//TODO add info of remaining build time and queue infos
					//actionLog(""+culang.tabLabelAutoBuild+"",Cities.cities[i].name+" : occupe.");
					if (i >= Cities.cities.length-1) {
						setTimeout(function() { t.e_autoBuild(cityId);  }, 10000); //should be at least 7.5 
					}
				} else {
					if (t["bQ_" + cityId].length > 0) { // something to do?
						var bQi = t["bQ_" + cityId][0];   //take first queue item to build
						//actionLog(""+culang.tabLabelAutoBuild+"",Cities.cities[i].name+" : Tentative de construction...");
						t.doOne(bQi);
						setTimeout(function() {

							t.e_autoBuild(cityId);

						},10000); //should be at least 10
						break; // Am?liorations pour pas lancer tout en meme temps = risque de Captcha ou backOffWaitTime

					} else {
						//actionLog(""+culang.tabLabelAutoBuild+"",Cities.cities[i].name+" : rien. " + i + " >= " + Cities.cities.length);	
						if (i >= Cities.cities.length-1) {
							setTimeout(function() { t.e_autoBuild(cityId);  }, 10000); //should be at least 7.5 
						}
					}
				}

			}


		}

	},
	doOne : function (bQi){
		var t = Tabs.build;
		var currentcityid = parseInt(bQi.cityId);
		var cityName = t.getCityNameById(currentcityid);
		var time = parseInt(bQi.buildingTime);
		var mult = parseInt(bQi.buildingMult);
		var attempt = parseInt(bQi.buildingAttempt);
		var mode = bQi.buildingMode;
		var citpos = parseInt(bQi.buildingPos);
		if (Seed.buildings['city' + currentcityid]["pos" + citpos] != undefined && Seed.buildings['city' + currentcityid]["pos" + citpos][0] != undefined) {
			var l_bdgid = parseInt(bQi.buildingType);
			var bdgid = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][0]);
			var l_curlvl = parseInt(bQi.buildingLevel);
			var curlvl = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][1]);
			var l_bid = parseInt(bQi.buildingId);
			var bid = parseInt(Seed.buildings["city" + currentcityid]["pos" + citpos][3]);

			if (curlvl > 8 && mode == 'build') {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogLevel9OrHigher+"");
				return;
			};
			if (isNaN(curlvl)) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogWrongLevel+"");
				return;
			}
			if (l_bdgid != bdgid) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingType+"");
				return;
			}
			if (l_bid != bid) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingID+"");
				return;
			}
			if (l_curlvl < curlvl) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingEqualHigher+"");
				return;
			}
			if (l_curlvl > curlvl && mode == 'build') {
				t.requeueQueueElement(bQi);
				return;
			}

			if (mode == 'destruct') {
				var params = uW.Object.clone(uW.g_ajaxparams);
				params.cid = currentcityid;
				params.bid = "";
				params.pos = citpos;
				params.lv = curlvl - 1;
				if (curlvl >= 1) {
					params.bid = bid;
				}
				params.type = bdgid;
				new MyAjaxRequest(uW.g_ajaxpath + "ajax/destruct.php" + uW.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					onSuccess: function(rslt){
						if (rslt.ok) {
							actionLog(""+culang.tabLabelAutoBuild+"",cityName + ": "+culang.buildLogDestructRessource+"");
							Seed.queue_con["city" + currentcityid].push([bdgid, 0, parseInt(rslt.buildingId), uW.unixtime(), uW.unixtime() + rslt.timeNeeded, 0, rslt.timeNeeded, citpos]);
							if (params.cid == uW.currentcityid) {
								uW.update_bdg();
								uW.queue_changetab_building();
							}
							t.cancelQueueElement(0, currentcityid, time, false);
						} else {
							var errmsg = rsltErrorCode(rslt);
							actionLog(""+culang.tabLabelAutoBuild+"",cityName + ": " + errmsg);
							t.requeueQueueElement(bQi);
							ById('pbbuildError').innerHTML = errmsg;

						}
					},
					onFailure: function(){
						ById('pbbuildError').innerHTML = ""+culang.buildLogDestructError+"";
					}
				})
			}
			if (mode == 'build') {
				var invalid = false;
				var chk = uW.checkreq("bdg", bdgid, curlvl);
				for (var c = 0; c < chk[3].length; c++) {
					if (chk[3][c] == 0) {
						invalid = true;
					}
				}
				if (invalid == false) {
					var params = uW.Object.clone(uW.g_ajaxparams);
					params.cid = currentcityid;
					params.bid = "";
					params.pos = citpos;
					params.lv = curlvl + 1;
					if (params.lv > 9){
						t.cancelQueueElement(0, currentcityid, time, false);
						actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingLevelTen+"");
						return;
					}
					if (params.lv > 1) {
						params.bid = bid;
					}
					params.type = bdgid;


					// NOUVEAU ! Test si vous avez assez de matos ^^^
					if ((Seed.resources["city" + currentcityid].rec1[0] >= parseInt(uW.buildingcost["bdg" + bdgid][1]) * mult * 3600) &&
						(Seed.resources["city" + currentcityid].rec2[0] >= parseInt(uW.buildingcost["bdg" + bdgid][2]) * mult * 3600) &&
						(Seed.resources["city" + currentcityid].rec3[0] >= parseInt(uW.buildingcost["bdg" + bdgid][3]) * mult * 3600) &&
						(Seed.resources["city" + currentcityid].rec4[0] >= parseInt(uW.buildingcost["bdg" + bdgid][4]) * mult * 3600) &&
						(Seed.citystats["city" + currentcityid].gold[0] >= parseInt(uW.buildingcost["bdg" + bdgid][5]) * mult)) {



						new MyAjaxRequest(uW.g_ajaxpath + "ajax/construct.php" + uW.g_ajaxsuffix, {
							method: "post",
							parameters: params,
							onSuccess: function(rslt){
								if (rslt.ok) {
									actionLog(""+culang.tabLabelAutoBuild+"",Cities.byID[currentcityid].name + " - " + uW.buildingcost["bdg" + bdgid][0] + ' Level ' + (curlvl + 1)); 
									Seed.resources["city" + currentcityid].rec1[0] -= parseInt(uW.buildingcost["bdg" + bdgid][1]) * mult * 3600;
									Seed.resources["city" + currentcityid].rec2[0] -= parseInt(uW.buildingcost["bdg" + bdgid][2]) * mult * 3600;
									Seed.resources["city" + currentcityid].rec3[0] -= parseInt(uW.buildingcost["bdg" + bdgid][3]) * mult * 3600;
									Seed.resources["city" + currentcityid].rec4[0] -= parseInt(uW.buildingcost["bdg" + bdgid][4]) * mult * 3600;
									Seed.citystats["city" + currentcityid].gold[0] -= parseInt(uW.buildingcost["bdg" + bdgid][5]) * mult;
									Seed.queue_con["city" + currentcityid].push([bdgid, curlvl + 1, parseInt(rslt.buildingId), uW.unixtime(),  uW.unixtime() + rslt.timeNeeded, 0, rslt.timeNeeded, citpos]);
									if (params.cid == uW.currentcityid) {
										uW.update_bdg();
										uW.queue_changetab_building();
									}
									if (ById('pbHelpRequest').value != 'off')
										t.bot_gethelp(params.bid, currentcityid, rslt.timeNeeded);
									t.cancelQueueElement(0, currentcityid, time, false);
								} else {
									if (rslt.user_action) {
										if (rslt.user_action!="backOffWaitTime") {
											actionLog(""+culang.tabLabelAutoBuild+"","<b><font color=red>Detection Captcha  !!!</font></b>");
											new CdialogCancelContinue('<SPAN class=boldRed>CAPTCHA ALERT ! Trop de construction !</span>', null, null, mainPop.getMainDiv);
										}

									} else {
										var errmsg = rsltErrorCode(rslt);
										if (rslt.error_code == 103) {
											t.cancelQueueElement(0, currentcityid, time, false);
											actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +": "+culang.buildLogBuildingProcess2+"");
										} else {
											t.requeueQueueElement(bQi);
											actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +' : '+ errmsg);
											ById('pbbuildError').innerHTML = Cities.byID[currentcityid].name +': '+ errmsg + " "+culang.buildLogBuildingProcessAgain+"";
										}
									}

								}
							},
							onFailure: function(){
								ById('pbbuildError').innerHTML = ""+culang.buildConnectError+"";
							}
						});

					} else {
						t.requeueQueueElement(bQi);
						actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +' : <font color=red>'+culang.buildLogNoRessource+'</font>');
					}


				} else {
					t.requeueQueueElement(bQi);
					//actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +' : <font color=red>Bizarreee !!</font>'); 
					t.countbizarre++;
					if (t.countbizarre>10) {
						actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildBuildTenFaild+"");
						reloadKOC();

					}
				}
			}
		} else {
			t.cancelQueueElement(0, currentcityid, time, false);
			//actionLog(""+culang.tabLabelAutoBuild+"","Queue item deleted: Building does not exist!!!");
		}
	},
	countbizarre:0,
	requeueQueueElement: function (bQi) {
		var t = Tabs.build;
		var cityId = bQi.cityId;
		var buildingPos = parseInt(bQi.buildingPos);
		var buildingId = parseInt(bQi.buildingId);
		var buildingLevel = parseInt(bQi.buildingLevel);
		var buildingType = parseInt(bQi.buildingType);
		var buildingTime = parseInt(bQi.buildingTime);
		var buildingMult = parseInt(bQi.buildingMult);
		var buildingAttempts = parseInt(bQi.buildingAttempts);
		var buildingMode = bQi.buildingMode;

		t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts + 1, buildingMult, buildingMode);
		t.cancelQueueElement(0, cityId, buildingTime, false);
	},
	show: function(){
		var t = Tabs.build;
	},
	bot_buildslot: function(c, a){
		var t = Tabs.build;
		var cityId = t.getCurrentCityId();
		var buildingPos   = c.id.split("_")[1];
		var buildingType  = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][0]);
		var buildingLevel = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
		var buildingId    = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][3]);
		var buildingAttempts = 0;
		var loaded_bQ = t["bQ_" + cityId];
		if (typeof Seed.queue_con['city' + cityId][0] != 'undefined') {
			var current_construction_pos = Seed.queue_con['city' + cityId][0][2];
		} else {
			var current_construction_pos = "";
		}
		if (loaded_bQ.length == 0 && current_construction_pos != "" ) {
			if (current_construction_pos != 'NaN' && current_construction_pos == buildingId) {
				buildingLevel += 1;
			}
		} else {
			if (current_construction_pos != "" && current_construction_pos == buildingId) {
				buildingLevel += 1;
			}
			for (var i = 0; i < loaded_bQ.length; i++) {
				var loadedCity = loaded_bQ[i].cityId;
				var loadedSlot = loaded_bQ[i].buildingPos;
				if (loadedSlot == buildingPos && loadedCity == cityId) {
					buildingLevel += 1;
				}
				if (loaded_bQ[i].buildingMode == 'destruct' && loadedSlot == buildingPos && loadedCity == cityId) {
					t.modalmessage(''+culang.buildDestrucAlreadyInQueue+'');
					return;
				}
			}
		}
		if (t.currentBuildMode == "build") {
			if (buildingLevel >= 9) {
				t.modalmessage(''+culang.buildBuildTryedLevelTen+'');
				return;
			}
			var buildingMode = "build";
			var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
			var buildingMult = result[0];
			var buildingTime = result[1];
			var queueId = loaded_bQ.length;
			t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
			t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
		}
		if (t.currentBuildMode == "max") {
			var buildingMode = "build";
			for (var bL = buildingLevel; bL <9; bL++) {
				var queueId = loaded_bQ.length;
				var result = t.calculateQueueValues(cityId, bL, buildingType, buildingMode);
				var buildingMult = result[0];
				var buildingTime = result[1];
				queueId = queueId ;
				t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult, buildingMode);
				t._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
			}
		}
		if (t.currentBuildMode == "destruct") {
			var buildingMode = "destruct";
			var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
			var buildingMult = result[0];
			var buildingTime = result[1];
			var queueId = loaded_bQ.length;
			t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
			t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
		}
		if (t.currentBuildMode == "destructnow") {

			var params = uW.Object.clone(uW.g_ajaxparams);
			params.cityId = cityId;
			params.buildingId = buildingId;
			params.pos = buildingPos;
			params.requestType = "DESTROY_BUILDING_DRAGON_STOMP_MEDAL";
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/destroyBuilding.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function(rslt){
					if (rslt.ok) {
						uW.seed.items.i9=Number(uW.seed.items.i9)-1;
						uW.ksoItems[9].subtract();

						delete Seed.buildings["city"+cityId]["pos"+buildingPos];

						uW.citysel_click(ById("citysel_"+(Cities.byID[cityId].idx+1)));

					} else {
						var errmsg = uW.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);

						ById('pbbuildError').innerHTML = errmsg;

					}
				},
				onFailure: function(){
					ById('pbbuildError').innerHTML = "Error for Destruction!";
				}
			})


		}

	},
	calculateQueueValues: function (cityId, buildingLevel, buildingType, buildingMode) {
		var t = Tabs.build;
		var now = unixTime();
		if (buildingMode == 'build') {
			var buildingMult = Math.pow(2, buildingLevel);
		}
		if (buildingMode == 'destruct') {
			var buildingMult = Math.pow(2, buildingLevel - 2);
		}

		var knights = Seed.knights["city" + cityId];
		if (knights) {
			var polKniId = parseInt(Seed.leaders['city' + cityId].politicsKnightId);
			if (polKniId) {
				var polValue = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politics);
				var polBoost = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politicsBoostExpireUnixtime);
				if ((polBoost - now) > 0) {
					polValue = parseInt(polValue * 1.25);
				}
			} else {
				polValue = 0;
			}
		} else {
			polValue = 0;
		}

		var buildingTime = uW.buildingcost["bdg" + buildingType][7] * buildingMult;

		if (parseInt(buildingType) < 6 && parseInt(buildingType) > 0 && buildingMult == 1) {
			buildingTime = 15;
		}

		var MaxBuild = uW.cm.thronestats.boosts.ConstructionSpeed.Max;
		var TR = Math.min(uW.cm.ThroneController.effectBonus(78), MaxBuild);
	
		if (buildingMode == 'build') {
			buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));

		}
		if (buildingMode == 'destruct') {
			buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));
			if (buildingTime % 1 > 0) {
				buildingTime = parseInt(buildingTime);
			}
		}
		buildingTime=Math.round(buildingTime/(1+(TR/100)));
		var result = new Array(buildingMult, buildingTime);
		return result;
	},

	bot_gethelp: function (f, currentcityid, time) {
		var t = Tabs.build;
	
		//Chat Anfrage
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.bid = f;
		params.ctrl = 'AskForHelp';
		params.action = 'getHelpData';
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				uW.handleHelpCallback (rslt.data);
			},
			onFailure: function (rslt) {
				t.bot_gethelp (f, currentcityid, time);
				return;
			},
		});
		
		//FB Anfrage
		var help = ById('pbHelpRequest').value;
		if (help == 'off' || help == 'chat') return;
		if (help == 'chatfb10' && time < 600) return;
		if (help == 'chatfb20' && time < 1200) return;
		if (help == 'chatfb30' && time < 1800) return;
		if (help == 'chatfb60' && time < 3600) return;
		var a = Seed.queue_con["city" + currentcityid];
		var e = 0;
		var d = 0;
		for (var c = 0; c < a.length; c++) {
			if (parseInt(a[c][2]) == parseInt(f)) {
				e = parseInt(a[c][0]);
				d = parseInt(a[c][1]);
				break;
			}
		}
		var b = new Array();
		b.push(["REPLACE_CiTyId", currentcityid]);
		b.push(["REPLACE_LeVeLbUiLdInG", d]);
		b.push(["REPLACE_BuIlDiNgNaMe", uW.buildingcost["bdg" + e][0]]);
		b.push(["REPLACE_LeVeLiD", d]);
		b.push(["REPLACE_AsSeTiD", f]);
		var g = function(h, i) {
			uW.continuation_95(h, i);
			if (!h) {
				var j = d > 1 ? uW.cm.SpeedUpType.upgrade : uW.cm.SpeedUpType.build;
				uW.cm.ClientSideCookieManager.setCookie(j, false)
			}
		};
		uW.common_postToProfile("95", uW.Object.cloneFeed(uW.template_data_95), uW.Object.cloneFeed(uW.actionlink_data_95), g, b)
	},
	addQueueItem: function (cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode) {
		var t = Tabs.build;
		var lbQ = t["bQ_" + cityId];
		lbQ.push({
			cityId: 			cityId,
			buildingPos:		buildingPos,
			buildingType: 		buildingType,
			buildingId: 		buildingId,
			buildingTime: 		buildingTime,
			buildingLevel: 		buildingLevel,
			buildingAttempts: 	buildingAttempts,
			buildingMult: 		buildingMult,
			buildingMode: 		buildingMode
		});
		t.modifyTotalTime(cityId, 'increase', buildingTime);
	},
	modalmessage: function(message){
		var t = Tabs.build;
		var timeout = 10000;
		var content = ""+culang.buildAutoCloseIn10Seconds+"<br>"
		content += message;
		uW.Modal.showAlert(content);
		setTimeout(function() {
			uW.Modal.hideModal();
		}, timeout);
	},
	modifyTotalTime: function (cityId, type, buildingTime) {
		var t = Tabs.build;
		var element = ById('pbbuildcount_' + cityId);
		var currentCount = parseInt(element.innerHTML);
		if (type == "increase") {
			t['totalTime_' + cityId] = t['totalTime_' + cityId] + buildingTime;
			var currentCount = currentCount + 1;
		}
		if (type == "decrease") {
			t['totalTime_' + cityId] = t['totalTime_' + cityId] - buildingTime;
			var currentCount = currentCount - 1;
		}
		element.innerHTML = currentCount;
		ById('pbbuildtotal_' + cityId).innerHTML = timestr(t['totalTime_' + cityId]);
	},
	hide: function(){
		var t = Tabs.build;
	},
	onUnload: function(){
		var t = Tabs.build;
		for (var i = 0; i < Cities.cities.length; i++) {
			t["bQ_" + Cities.cities[i].id].sort(function(a,b){return a.buildingTime - b.buildingTime});
			if (!ResetAll) GM_setValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, JSON2.stringify((t["bQ_" + Cities.cities[i].id])));
		}
		t.saveBuildStates();
	},
	_addTab: function(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode){
		var t = Tabs.build;
		var row = ById('pbCityQueueContent').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = queueId;
		if (buildingMode == "destruct") {
			row.insertCell(1).innerHTML = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/bonus_att.png">';
		}
		else {
			row.insertCell(1).innerHTML = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/bonus_prod.png">';
		}
		row.insertCell(2).innerHTML = uW.buildingcost['bdg' + buildingType][0];
		row.insertCell(3).innerHTML = timestr(buildingTime);
		if (buildingMode == "destruct") {
			row.insertCell(4).innerHTML = 0;
		} else {
			row.insertCell(4).innerHTML = buildingLevel + 1;
		}
		row.insertCell(5).innerHTML = buildingAttempts;
		row.insertCell(6).innerHTML = '<a id="queuecancel_' + queueId + '"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a>';
		ById('queuecancel_' + queueId).addEventListener('click', function(){
			t.cancelQueueElement(queueId, cityId, buildingTime, true);
		}, false);
	},
	cancelQueueElement: function(queueId, cityId, buildingTime, showQueue){
		var t = Tabs.build;
		var queueId = parseInt(queueId);
		t["bQ_" + cityId].splice(queueId, 1);
		t.modifyTotalTime(cityId, 'decrease', buildingTime);

		if (showQueue == true) {
			t.showBuildQueue(cityId, false);
		}
	},
	showBuildQueue: function(cityId, focus){
		var t = Tabs.build;
		clearTimeout (t.timer);
		var popBuildQueue = null;
		var cityName = t.getCityNameById(cityId);
		if (t.popBuildQueue == null) {
			t.popBuildQueue = new CPopup('pbbuild_' + cityId, 0, 0, 350, 500, true, function() {clearTimeout (t.timer);});
		}
		var m = '<DIV style="max-height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTabPad" id="pbCityQueueContent">';
		t.popBuildQueue.getMainDiv().innerHTML = '</table></div>' + m;
		t.popBuildQueue.getTopDiv().innerHTML = '<div class="popupBanner">' + cityName + ': <INPUT id=pbOptimizeByTime type=submit value="'+culang.buildBuildQueueSort+'"></div>';
		t.popBuildQueue.centerMe (mainPop.getMainDiv());

		t.paintBuildQueue(cityId);
		if (focus)
			t.popBuildQueue.show(true);
		ById('pbOptimizeByTime').addEventListener('click', function(){t.clearBuildQueue();t.paintBuildQueue(cityId, true);}, false);
		t.timer = setTimeout (function() {t.showBuildQueue(cityId, false)}, 45000);
	},
	paintBuildQueue: function(cityId, optimize){
		var t = Tabs.build;
		var lbQ = t["bQ_" + cityId];
		if (optimize == true) {
			lbQ.sort(function(a,b){return a.buildingTime - b.buildingTime});
		}
		t["bQ_" + cityId] = lbQ;
		for (var i = 0; i < lbQ.length; i++) {
			var queueId = i;
			t._addTab(queueId, lbQ[i].cityId, lbQ[i].buildingType, lbQ[i].buildingTime, lbQ[i].buildingLevel, lbQ[i].buildingAttempts, lbQ[i].buildingMode);
		}
	},
	clearBuildQueue: function() {
		var t = Tabs.build;
		var table = ById('pbCityQueueContent');
		var rows = table.rows;
		while(rows.length)
			table.deleteRow(rows.length-1);
	},
	getCurrentCityId: function(){
		if (!uW.currentcityid)
			return null;
		return uW.currentcityid;
	},
	saveBuildStates: function(){
		var t = Tabs.build;
		var serverID = getServerId();
		GM_setValue('buildStates_' + serverID, JSON2.stringify(t.buildStates));
	},
	readBuildStates: function(){
		var t = Tabs.build;
		var serverID = getServerId();
		s = GM_getValue('buildStates_' + serverID);
		if (s != null) {
			states = JSON2.parse(s);
			for (k in states)
				t.buildStates[k] = states[k];
		}
	},
	toggleBuildStateRunning: function(obj){
		var t = Tabs.build;
		obj = ById('pbBuildRunning');
		if (t.buildStates.running == true) {
			t.buildStates.running = false;
			t.saveBuildStates();
			if (obj) obj.value = culang.buildButton+" = "+culang.buttonOFF;
		}
		else {
			t.buildStates.running = true;
			t.saveBuildStates();
			if (obj) obj.value = culang.buildButton+" = "+culang.buttonON;
			setTimeout(t.UseSpeedup,1000);			
			t.e_autoBuild(0);
		}
	},
	toggleStateMode: function(obj){
		var t = Tabs.build;
		obj = ById('pbBuildMode');
		if (obj.value == culang.buildMode+' = '+culang.buttonOFF) {
			uW.buildslot = t.bot_buildslot;
			obj.value = culang.buildMode+' = '+culang.buttonON;

		} else {
			uW.buildslot = t.koc_buildslot;
			obj.value = culang.buildMode+' = '+culang.buttonOFF;
		}
	},
	getCityNameById: function (cityId) {
		return Cities.byID[cityId].name;
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/DarkForest.js">
//	
//	   KOC POWER - TABS DARKFOREST										        
//	
var DFOptions = {
  LastSearch: 0,
  Running: false,
  DFFound: 0,
	Radius: 35,	
	Interval: 20,
	Method: "distance",
	Knightselector: "0",
	Levels: {
		1: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},
		2: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		3: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		4: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		5: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},
		6: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		7: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		8: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
	},
	Troops: {
		1:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		2:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		3:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		4:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		5:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		6:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		7:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		8:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		9:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		10: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
	},
};
function saveDFOptions (){ var serverID = getServerId(); setTimeout (function (){GM_setValue ('DFOptions' + Seed.player['name'] + '_' +serverID, JSON2.stringify(DFOptions));}, 0);}
function readDFOptions (){ var serverID = getServerId(); s = GM_getValue ('DFOptions'+Seed.player['name']+'_'+serverID, '[]'); if (s != null){ opts = JSON2.parse (s); for (k in opts){ if (matTypeof(opts[k]) == 'object') for (kk in opts[k]) DFOptions[k][kk] = opts[k][kk]; else if (DFOptions[k] != undefined) DFOptions[k] = opts[k]; } } }

Tabs.DF = {
	tabLabel: culang.mainDarkForest,
	tabOrder: TabOptions.toDarkForest,
	myDiv: null,
	statsTimer : null,
	DFArray: {},
	mapblocks: [],
	mapDat: [],
	
	init: function (div) {
		var t = Tabs.DF;
		t.myDiv = div;
		readDFOptions();
		if (!DFOptions.Radius) DFOptions.Radius = 35;
		if (DFOptions.Radius > 45) DFOptions.Radius = 45;
		if (DFOptions.Method != "distance" && DFOptions.Method != "level" && DFOptions.Method != "lowlevel") DFOptions.Method = "distance";
		var m = '<DIV id=pbReinfMain class=pdxStat>' + culang.dfHead + '</div><table class=pdxTab width=100%><tr>';
		if (DFOptions.Running == false) {
			m += '<TD><INPUT id=AttSearch type=submit value="' + culang.mainDarkForest + ' = ' + culang.buttonOFF + '"></td>';
		} else {
			m += '<TD><INPUT id=AttSearch type=submit value="' + culang.mainDarkForest + ' = ' + culang.buttonON + '"></td>';
		}
		m += '<td align=center><INPUT id=pbDFShow type=submit class=pbButton value="' + culang.mainShow + '">&nbsp<INPUT id=pbReset type=submit class=pbButton value="' + culang.dfRetrySearch + '"></td>';
		m += '<td align=center>'+culang.DFRadius +'<INPUT id=pbDFRadius type=text value="' + DFOptions.Radius + '" style="width:30px;text-align:center;">';
		m += '<br>'+culang.DFInterval +'<INPUT id=pbDFInterval type=text value="' + DFOptions.Interval + '" style="width:30px;text-align:center;">';
		m += '</td>';
		m += '<TD align=right>'+culang.OlddfMethode+': '+htmlSelector({distance:culang.mainDistance, level:culang.OlddfSelectMethodeHighLevel, lowlevel:culang.OlddfSelectMethodeLowLevel}, DFOptions.Method, 'id=pbdfmethod style="width:200px;"')+'<br>';
		var yy = htmlSelector({0:culang.OlddfSelectKnightLowCom, 1:culang.OlddfSelectKnightHighCom, 2:culang.OlddfSelectKnightLowPol, 3:culang.OlddfSelectKnightHighPol, 4:culang.OlddfSelectKnightLowInt, 5:culang.OlddfSelectKnightHighInt, 6:culang.OlddfSelectKnightLowRes, 7:culang.OlddfSelectKnightHighRes, 8:culang.OlddfSelectKnightLowSum, 9:culang.OlddfSelectKnightHighSum}, DFOptions.Knightselector, 'id=dfknightselect style="width:200px;"');
		m += culang.OlddfKnightSelector+': '+yy+'</td>';
		m += '</tr></table>';
		m += '<DIV id=DFStats text-align=center></div>';
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.DFattackStats + '</div>';
		m += '<div id=pbdfattackstats></div>';
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.dfSettingsHead + '</div>';

		m += '<TABLE width=100%>';
		for (i = 0; i < Seed.cities.length; i++) {
			m += '<TR><TD>' + Seed.cities[i]["1"] + '</td>';
			for (y = 1; y <= 10; y++) m += '<TD class=DFLevelopt><INPUT id=DFcity' + i + 'level' + y + ' type=checkbox unchecked=true>' + culang.dfTroopSelectLvl + '' + y + '</td>';
		}
		m += '</table>';
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.dfSelectTroopsHead + '</div>';
		m += '<TABLE width=100%><TR><TD></td>';
		for (var i = 1; i <= 12; i++) m += '<TD align=center><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg" title="' + uW.unitcost['unt' + i][0] + '"></td>';
		for (i = 1; i <= 10; i++) {
			m += '</tr><TR><TD>' + uW.g_js_strings.commonstr.level + ' ' + i + ': </td>';
			for (var j = 1; j <= 12; j++) m += '<TD align=center class=DFTroopOpt><INPUT id="DFlevel' + i + 'troop' + j + '" type=text size=4 maxlength=6 value="' + DFOptions.Troops[i][j] + '" /></td>';
		}
		m += '</tr></table><sup><span class=boldRed><u>' + culang.mainImportant + '</u></span>:</sup> <span class=helpText>' + culang.dfHeadDFTroopsNote + '</span>';

		t.myDiv.innerHTML = m;

		for (i = 0; i < Seed.cities.length; i++)
			for (w = 1; w <= 10; w++) document.getElementById('DFcity' + i + 'level' + w).checked = DFOptions.Levels[i + 1][w];
		document.getElementById('pbReset').addEventListener('click', t.ResetDFData, false);
		var element_class = document.getElementsByClassName('DFLevelopt');
		for (k = 0; k < element_class.length; k++) element_class[k].addEventListener('click', t.saveLevelOptions, false);
		var element_class = document.getElementsByClassName('DFTroopOpt');
		for (k = 0; k < element_class.length; k++) element_class[k].addEventListener('change', t.saveTroopOptions, false);
		document.getElementById('AttSearch').addEventListener('click', function () {
			t.toggleDFState()
		}, false);
		document.getElementById('pbDFShow').addEventListener('click', function () {
			t.ShowDFArray()
		}, false);
		document.getElementById('pbDFRadius').addEventListener('change', function () {
			var value = parseIntNan(document.getElementById('pbDFRadius').value);
			if (value < 20) value = 20;
			if (value > 45) value = 45;
			document.getElementById('pbDFRadius').value = value;
			DFOptions.Radius = value;
			saveDFOptions();
		}, false);
		document.getElementById('pbDFInterval').addEventListener('change', function () {
			var value = parseIntNan(document.getElementById('pbDFInterval').value);
			if (value < 20) value = 20;
			if (value > 240) value = 240;
			document.getElementById('pbDFInterval').value = value;
			DFOptions.Interval = value;
			saveDFOptions();
		}, false);
		ById('pbdfmethod').addEventListener('change', function(){
			DFOptions.Method = ById('pbdfmethod').value;
			saveDFOptions();
			//Neu sortieren!!!
			for (i = 0; i < Seed.cities.length; i++) {
				var helpArray = JSON2.parse(GM_getValue('DarkForest_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), "[]"));
				t.DFArray[i] = [];
				if (helpArray) {
					if(DFOptions.Method == 'distance') t.DFArray[i] = helpArray.sort(function sort(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
					if(DFOptions.Method == 'level') t.DFArray[i] = helpArray.sort(function sort(a,b) {a = parseInt(a['Level']);b = parseInt(b['Level']);return a == b ? 0 : (a > b ? -1 : 1);});
					if(DFOptions.Method == 'lowlevel') t.DFArray[i] = helpArray.sort(function sort(a,b) {a = parseInt(a['Level']);b = parseInt(b['Level']);return a == b ? 0 : (a < b ? -1 : 1);});
				}
			}
		},false);
		ById('dfknightselect').addEventListener('change', function(){
			DFOptions.Knightselector=ById('dfknightselect').value;
			saveDFOptions();
		},false);
		var now = unixTime();
		document.getElementById('DFStats').innerHTML = "<b>" + culang.dfLastSearch + "</b> <i><span class='boldRed'>" + FullDateTime(DFOptions.LastSearch) + "</span></i> <b>" + culang.dfLastSearch2 + "</b> <i><span class='boldRed'>" + DFOptions.DFFound + "</span> " + culang.dfLastSearch3 + "</i>";
		if ((DFOptions.LastSearch + (DFOptions.Interval * 60)) < now && DFOptions.Running) t.ResetDFData();
		else {
			for (i = 0; i < Seed.cities.length; i++) {
				var helpArray = JSON2.parse(GM_getValue('DarkForest_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), "[]"));
				t.DFArray[i] = [];
				if (helpArray) {
					if(DFOptions.Method == 'distance') t.DFArray[i] = helpArray.sort(function sort(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
					if(DFOptions.Method == 'level') t.DFArray[i] = helpArray.sort(function sort(a,b) {a = parseInt(a['Level']);b = parseInt(b['Level']);return a == b ? 0 : (a > b ? -1 : 1);});
					if(DFOptions.Method == 'lowlevel') t.DFArray[i] = helpArray.sort(function sort(a,b) {a = parseInt(a['Level']);b = parseInt(b['Level']);return a == b ? 0 : (a < b ? -1 : 1);});
				}
			}
		}
		t.statsTimer = setInterval(t.showStats, 1000);
	},
	showStats: function() {
		var t = Tabs.DF;
		var m = '<table width=100%><tr>';
		for (i = 0; i < Seed.cities.length; i++) {
			m += '<td width=13% align=center><b>' + Cities.cities[i].name + '</b><br>' + t.DFArray[i].length + '</td>';
		}
		m += '</tr></table>';
		ById('pbdfattackstats').innerHTML = m;
	},
	ShowDFArray: function () {
		var t = Tabs.DF;
		var m = '<TABLE id=pbDF width=80% height=0% class=pdxTab>';
		for (i = 0; i < Seed.cities.length; i++) {
			if (t.DFArray[i].length > 0) {
				m += '<TR><TD colspan=5 style=\'background: #335577;\' align=center><B><FONT color=white>' + Seed.cities[i][1] + ': </font></b></td></tr>';
				for (var k in t.DFArray[i])
					if (t.DFArray[i][k].dist) {
						if (t.DFArray[i][k].Level >= 1 && t.DFArray[i][k].Level <= 3) var Tlevel = 1;
						if (t.DFArray[i][k].Level >= 4 && t.DFArray[i][k].Level <= 6) var Tlevel = 4;
						if (t.DFArray[i][k].Level >= 7) var Tlevel = 7;
						m += '<TR><TD><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">(' + t.DFArray[i][k].X + ',' + t.DFArray[i][k].Y + ')</a></td><TD width=50px><img width=50px src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/boss_lvl' + Tlevel + '.png"></td><TD>' + culang.dfTroopSelectLvl + ' ' + t.DFArray[i][k].Level + '</td><TD>' + culang.dfTroopSelectDist + ' ' + t.DFArray[i][k].dist + '</td></tr>';
					}
			}
		}
		var pop = new CPopup('DFArray', 0, 0, 550, 410, true);
		pop.centerMe(mainPop.getMainDiv());
		pop.getMainDiv().innerHTML = '<DIV style="width:550px;max-width:550px;max-height:410px;overflow:auto">' + m + '</div>';
		pop.getTopDiv().innerHTML = '<div class="popupBanner">' + culang.dfPopupHead + '</div>';
		pop.show(true);

	},

	toggleDFState: function (obj) {
		var t = Tabs.DF;
		var now = unixTime();
		obj = ById('AttSearch');
		if (DFOptions.Running == true) {
			DFOptions.Running = false;
			obj.value = culang.mainDarkForest + " = " + culang.buttonOFF;
			ClearMarchQueue("" + culang.mainDarkForest + "");
			saveDFOptions();
		} else {
			if ((DFOptions.LastSearch + (DFOptions.Interval * 60)) < now) t.ResetDFData();
			DFOptions.Running = true;
			obj.value = culang.mainDarkForest + " = " + culang.buttonON;
			saveDFOptions();
		}
	},
	saveLevelOptions: function () {
		for (i = 0; i < Seed.cities.length; i++) {
			DFOptions.Levels[i + 1][0] = false;
			for (w = 1; w <= 10; w++) {
				var ele = document.getElementById('DFcity' + i + 'level' + w);
				DFOptions.Levels[i + 1][w] = ele.checked;
				if (ele.checked) DFOptions.Levels[i + 1][0] = true;
			}
		}
		saveDFOptions();
	},

	saveTroopOptions: function () {
		for (i = 1; i <= 10; i++)
			for (w = 1; w <= 12; w++) DFOptions.Troops[i][w] = document.getElementById('DFlevel' + i + 'troop' + w).value;
		saveDFOptions();
	},

	doMarch: function (cityID, i) {
		var t = Tabs.DF;
		var now = unixTime();
		//Neu Suchen?
		if ((DFOptions.LastSearch + (DFOptions.Interval * 60)) < now) {
			t.ResetDFData();
			return false;
		}
		//Keine Koordinaten
		if (t.DFArray[i].length == 0) {
			/*
			var rep = {
				'city' : Cities.byID[cityID].name,
			};
			actionLog(culang.mainDarkForest,culang.DFAttackErr1.mreplace(rep));
			*/
			return false;
		}
		//Soll DF dieses Levels angegriffen werden?		
		var Level = parseInt(t.DFArray[i][0].Level);
		if (!DFOptions.Levels[i + 1][Level]) return;
		//Truppen MAX Kalkulation 
		var troops = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
		for (y = 1; y <= 12; y++) {
			if (DFOptions.Troops[Level][y] == "MAX") {
				var total = 0;
				for (var yy = 1; yy <= 12; yy++)
					if (y != yy) total += parseInt(DFOptions.Troops[Level][yy]);
				troops[y] = t.CalcMax(cityID, y) - total;
			} else troops[y] = DFOptions.Troops[Level][y];
		}
		//Genug Truppen in der Stadt?
		var ok = true;
		for (y = 1; y <= 12; y++) {
		 if (parseIntNan(Seed.units["city" + cityID]['unt'+y]) < troops[y]) ok = false;
		}
		if (ok == false) {
			var rep = {
				'city' : Cities.byID[cityID].name,
				'level' : t.DFArray[i][0].Level,
			};
			actionLog(culang.mainDarkForest,culang.DFAttackErr2.mreplace(rep));
			return false;
		}
		//Sind Truppen angegeben?
		var total = 0;
		for (y = 1; y <= 12; y++) {
		 total += troops[y];
		}
		if (total == 0) {
			var rep = {
				'level' : t.DFArray[i][0].Level,
			};
			actionLog(culang.mainDarkForest,culang.DFAttackErr3.mreplace(rep));
			return false;
		}
		//Sind Slot im Sammelplatz frei?
		var rinfo = getRallypointInfo(cityID);
		if (rinfo.freeSlots - Options.RPClip < 1) {
			var rep = {
				'city' : Cities.byID[cityID].name,
			};
			actionLog(culang.mainDarkForest,culang.DFAttackErr4.mreplace(rep));
			return false;
		}
		MarchQueue[i + 1].push({
			what: "DF",
			city: cityID,
			action: 4,
			targetX: t.DFArray[i][0].X,
			targetY: t.DFArray[i][0].Y,
			knight: DFOptions.Knightselector,
			1: troops[1],
			2: troops[2],
			3: troops[3],
			4: troops[4],
			5: troops[5],
			6: troops[6],
			7: troops[7],
			8: troops[8],
			9: troops[9],
			10: troops[10],
			11: troops[11],
			12: troops[12],
			13: 0,
			14: 0,
			15: 0,
			16: 0,
		});
		t.DFArray[i].splice(0, 1);
		GM_setValue('DarkForest_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), JSON2.stringify(t.DFArray[i]));
		return true;
	},

	ResetDFData: function () {
		var t = Tabs.DF;
		for (i = 0; i < Seed.cities.length; i++) GM_deleteValue('DarkForest_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), "[]")
		var ToSearch = [];
		var now = unixTime();
		for (i = 0; i < Seed.cities.length; i++) {
			AllEmpty = true;
			t.DFArray[i] = [];
			for (var y = 1; y <= 10; y++)
				if (DFOptions.Levels[i + 1][y]) AllEmpty = false;
			if (!AllEmpty) ToSearch.push(i);
		}
		if (ToSearch.length > 0) {
			DFOptions.LastSearch = now;
			DFOptions.DFFound = 0;
			saveDFOptions();
			t.mapblocks = [];
			document.getElementById('DFStats').innerHTML = '' + culang.searchStartSearching + ': <span id="SearchDF"></span> <span id="MapSearchActiveDF"></span>';
			for (i = 0; i < ToSearch.length; i++) {
				X = parseInt(Seed.cities[ToSearch[i]][2]);
				Y = parseInt(Seed.cities[ToSearch[i]][3]);
				t.MakeBlocks(X, Y, (ToSearch[i] + 1), (i + 1), ToSearch.length);
			}
			t.doSearch();
		}
	},

	MakeBlocks: function (getX, getY, city, i, length) {
		var t = Tabs.DF;
	
		var blocks = [];
		var xx = 0;
		var yy = 0;
		var blockcounter = 0;
		for (x = (getX - DFOptions.Radius); x <= (getX + DFOptions.Radius); x += 5) {
			for (y = (getY - DFOptions.Radius); y <= (getY + DFOptions.Radius); y += 5) {
				xx = x;
				yy = y;
				if (x > 750) xx -= 750;
				if (y > 750) yy -= 750;
				if (x < 0) xx += 750;
				if (y < 0) yy += 750;
				blocks.push("bl_" + xx + "_bt_" + yy);
				blockcounter++;
			}
		}
		//Aufteilen in kleinere Mengen a 20 blocks
		var max = ~~(blockcounter/searchblocks) + 1;
		var blo = [];
		for (var split = 0; split < max; split++) {
			blo = [];
			for (var z = 0; z < searchblocks; z++) {
				if (blocks.length > 0) {
					blo.push(blocks[0]);
					blocks.shift();
				}
			}
			var o = {
				'x'	: getX,
				'y'	: getY,
				'c'	: city,
				'i'	: i,
				'l'	: length,
				'm' : max,
				's' : split+1,
				'b'	: blo,
			};
			t.mapblocks.push(o);		
		}
	},
	
	doSearch: function () {
		var t = Tabs.DF;
		if (MapSearchActive == "") {
			MapSearchActive = culang.mainDarkForest;
		} 	
		if (MapSearchActive != culang.mainDarkForest)  {
			var rep = {
				'tab' : MapSearchActive,
			};
			ById('MapSearchActiveDF').innerHTML = culang.MapSearchActive.mreplace(rep);
			setTimeout(t.doSearch, 5000);
			return;
		} else if (t.mapblocks.length > 0) {
			ById('MapSearchActiveDF').innerHTML = '';
		}
		if (t.mapblocks.length > 0) {
			//Suchdaten auslesen
			var mdata = t.mapblocks[0];
			var blocks = mdata.b;
			var xx = mdata.x;
			var yy = mdata.y;
			var city = mdata.c;
			var i = mdata.i;
			var length = mdata.l;
			var max = mdata.m;
			var s = mdata.s;
		} else {
			//Keine weitern Suchdaten
			MapSearchActive = "";
			return;
		}
		
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = blocks;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
			try {
				if (rslt.ok) {
					if (rslt.error_code == 9) {
						//Map Error
						ById('MapSearchActiveDF').innerHTML = 'Map Error (60 Sec)';
						setTimeout(t.doSearch, 61000);
						return;
					}	
					ById('SearchDF').innerHTML = '('+i+'/'+length+') - ('+s+'/'+max+')';
					
					//Startet die Teilsuche?
					if (s == 1) t.mapDat = [];
					
					for (y in rslt.data) {
						if (rslt.data[y].tileType == 54 && DFOptions.Levels[city][parseInt(rslt.data[y].tileLevel)]) {
							var tileX = parseInt(rslt.data[y].xCoord);
							var tileY = parseInt(rslt.data[y].yCoord);
							var Level = parseInt(rslt.data[y].tileLevel);
							var dist = distance(xx, yy, tileX, tileY);
							t.mapDat.push({
								X: tileX,
								Y: tileY,
								Level: Level,
								dist: dist
							});
							DFOptions.DFFound++;
							
						}
					}
					saveDFOptions();
					
					//Teilsuche
					if (s == max) {
						//Teilsuche in der Stadt beendet
						GM_setValue('DarkForest_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.mapDat));
						var helpArray = JSON2.parse(GM_getValue('DarkForest_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), "[]"));
						if (helpArray) {
							if(DFOptions.Method == 'distance') t.DFArray[(city - 1)] = helpArray.sort(function sort(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
							if(DFOptions.Method == 'level') t.DFArray[(city - 1)] = helpArray.sort(function sort(a,b) {a = parseInt(a['Level']);b = parseInt(b['Level']);return a == b ? 0 : (a > b ? -1 : 1);});
							if(DFOptions.Method == 'lowlevel') t.DFArray[(city - 1)] = helpArray.sort(function sort(a,b) {a = parseInt(a['Level']);b = parseInt(b['Level']);return a == b ? 0 : (a < b ? -1 : 1);});
						}
						
					} 
					
					if (i == length && s == max) {
						//Suche Beendet
						ById('DFStats').innerHTML = "<b>" + culang.dfLastSearch + "</b> <i><span class='boldRed'>" + FullDateTime(DFOptions.LastSearch) + "</span></i> <b>" + culang.dfLastSearch2 + "</b> <i><span class='boldRed'>" + DFOptions.DFFound + "</span> " + culang.dfLastSearch3 + "</i>";
					}
					
					
				} else {
					actionLog(culang.mainDarkForest,inspect(rslt,5));
				}
				t.mapblocks.splice(0,1);
				setTimeout(t.doSearch, 500);
			} catch (ex) {
					alert('20491/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
			}
			},
			onFailure: function () {
				t.mapblocks.splice(0,1);
				setTimeout(t.doSearch, 500);
			},
		});
		
	},

	CalcMax: function (city, troop) {
		var t = Tabs.DF;
		var rinfo = getRallypointInfo(city);
		var maxsend = rinfo.maxMarchSize;
		return maxsend;
	},
	show: function () {
		var t = Tabs.DF;
		clearInterval(t.statsTimer);
		t.statsTimer = setInterval(t.showStats, 1000);
	},
	hide: function () {
		var t = Tabs.DF;
		clearInterval(t.statsTimer);
	},
	onUnload: function () {},
}
//</editor-fold>
function rsltErrorCode(rslt) {
	if (!rslt.error_code) return inspect(rslt,3);
	if (rslt.msg) return rslt.msg;
	var msg = uW.g_js_strings.errorcode["err_" + rslt.error_code].stripTags();
	return msg;
}

//<editor-fold desc="SPLIT:Tabs/Attack.js">
//	
//	   KOC POWER - TABS ATTACK											        
//	
var AtkOptions = {
	Running: false,
	1: [],
	2: [],
	3: [],
	4: [],
	5: [],
	6: [],
	7: [],
	8: [],
};
function saveAtkOptions() { var serverID = getServerId(); setTimeout(function () { GM_setValue('AtkOptions_' + Seed.player['name'] + '_' + serverID, JSON2.stringify(AtkOptions));	}, 0);}
function readAtkOptions() {	var serverID = getServerId(); s = GM_getValue('AtkOptions_' + Seed.player['name'] + '_' + serverID);if (s != null) {opts = JSON2.parse(s); for (k in opts) { if (matTypeof(opts[k]) == 'object') for (kk in opts[k])	if (matTypeof(opts[k][kk]) == 'object')	for (kkk in opts[k][kk]) AtkOptions_[k][kk][kkk] = opts[k][kk][kkk];else AtkOptions[k][kk] = opts[k][kk];else AtkOptions[k] = opts[k];}}}

Tabs.Attack = {
	tabOrder: TabOptions.toAttackTab,
	tabLabel: culang.mainAttack,
	myDiv: null,

	init: function (div) {
		var t = Tabs.Attack;
		t.myDiv = div;
		readAtkOptions();
		uW.RemoveAtkQueue = t.RemoveQueue;

		var m = '<DIV id=pbReinfMain class=pdxStat>' + culang.tabs_attack_head + '</div><TABLE id=pireinforce width=100% height=0% class=pdxTab><TR align="center">';
		if (AtkOptions.Running == false) {
			m += '<TD><INPUT id=AttackToggle type=submit value="' + culang.mainAttack + ' = ' + culang.buttonOFF + '"></td>';
		} else {
			m += '<TD><INPUT id=AttackToggle type=submit value="' + culang.mainAttack + ' = ' + culang.buttonON + '"></td>';
		}

		m += '<TABLE id=pbReinf width=95% height=0% class=pdxTab><TR align="left">';
		m += '<TD width="75px"><B><u>' + culang.mainCastle + ':</u></b></td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=pbAcityFrom></span></div></td>';
		m += '<TD width="60px"><B><u>' + culang.mainTarget + ':</u></b></td><TD><u><b>X:</b></u> <INPUT id=targetX type=text size=3>&nbsp&nbsp<u><b>Y:</b></u> <INPUT id=targetY type=text size=3></td></table>';
		m += '<TABLE id=pbMarch width=100% height=0% class=pdxTab><TR align="center"><TR><TR>';
		for (i = 1; i <= 4; i++) m += '<TD rowspan="3"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD>' + uW.unitnamedesctranslated["unt" + i][0] + '</td>';
		m += '</tr><TR>';
		for (i = 1; i <= 4; i++) m += '<TD><SPAN id=unit' + i + '></span></td>';
		m += '</tr><TR>';
		for (i = 1; i <= 4; i++) m += '<TD><INPUT id=Unt' + i + ' type=text size=10 maxlength=10 value="0"><INPUT id=Attack_Max' + i + ' type=submit value="' + culang.buttonMax + '"></td>';
		m += '</tr><TR>';
		for (i = 5; i <= 8; i++) m += '<TD rowspan="3"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD>' + uW.unitnamedesctranslated["unt" + i][0] + '</td>';
		m += '</tr><TR>';
		for (i = 5; i <= 8; i++) m += '<TD><SPAN id=unit' + i + '></span></td>';
		m += '</tr><TR>';
		for (i = 5; i <= 8; i++) m += '<TD><INPUT id=Unt' + i + ' type=text size=10 maxlength=10 value="0"><INPUT id=Attack_Max' + i + ' type=submit value="' + culang.buttonMax + '"></td>';
		m += '</tr><TR>';
		for (i = 9; i <= 12; i++) m += '<TD rowspan="3"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD>' + uW.unitnamedesctranslated["unt" + i][0] + '</td>';
		m += '</tr><TR>';
		for (i = 9; i <= 12; i++) m += '<TD><SPAN id=unit' + i + '></span></td>';
		m += '</tr><TR>';
		for (i = 9; i <= 12; i++) m += '<TD><INPUT id=Unt' + i + ' type=text size=10 maxlength=10 value="0"><INPUT id=Attack_Max' + i + ' type=submit value="' + culang.buttonMax + '"></td>';
		m += '</tr><TR>';
		for (i = 13; i <= 16; i++) m += '<TD rowspan="3"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD>' + uW.unitnamedesctranslated["unt" + i][0] + '</td>';
		m += '</tr><TR>';
		for (i = 13; i <= 16; i++) m += '<TD><SPAN id=unit' + i + '></span></td>';
		m += '</tr><TR>';
		for (i = 13; i <= 16; i++) m += '<TD><INPUT id=Unt' + i + ' type=text size=10 maxlength=10 value="0"><INPUT id=Attack_Max' + i + ' type=submit value="' + culang.buttonMax + '"></td>';
		m += '</tr><TR>';

		m += '</table><BR><TABLE id=pbReinfETA width=10% height=0% align="center" class=pdxTab>';
		m += '<TR align="center"><TD><a class="button20" id=AtkaddToQueue><span>' + culang.tabs_attack_savebutton + '</span></a></td></tr></table>';
		m += '<BR><DIV id=pbReinfMain class=pdxStat>' + culang.tabs_attack_savedmarchbutton + '</div><BR><BR><DIV id=AtkQueue></div>';

		t.myDiv.innerHTML = m;

		t.from = new CdispCityPicker('pbAfrom', document.getElementById('pbAcityFrom'), true, t.ClickCitySelect, 0);
		document.getElementById('AttackToggle').addEventListener('click', function () {
			t.toggleAttackState(this)
		}, false);

		for (i = 1; i <= 16; i++) document.getElementById('unit' + i).innerHTML = addCommas(Seed.units["city" + t.from.city.id]["unt" + i]);
		for (i = 1; i <= 16; i++) document.getElementById('Attack_Max' + i).addEventListener('click', function () {
			t.CalcMax(this.id)
		}, false);
		document.getElementById('AtkaddToQueue').addEventListener('click', t.GetCoords, false);
		t.PaintQueue();
	},
	toggleAttackState: function (obj) {
		var t = Tabs.Attack;
		obj = ById('AttackToggle');
		if (AtkOptions.Running == true) {
			AtkOptions.Running = false;
			if (obj) obj.value = culang.mainAttack + " = " + culang.buttonOFF;
			ClearMarchQueue("" + culang.mainAttack + "");
			saveAtkOptions();
		} else {
			AtkOptions.Running = true;
			if (obj) obj.value = culang.mainAttack + " = " + culang.buttonON;
			saveAtkOptions();
		}
	},

	GetCoords: function () {
		var t = Tabs.Attack;
		var targetName = "";
		var targetCityName = "";
		var tileLevel = 0;
		var total = 0;
		targetX = document.getElementById('targetX').value;
		targetY = document.getElementById('targetY').value;
		if (targetX == "" || targetY == "") {
			alert("" + culang.tabs_send_entercoords + "");
			return;
		}
		for (i = 1; i <= 16; i++) total += parseInt(document.getElementById('Unt' + i).value);
		if (total == 0) {
			alert("" + culang.tabs_send_send1trp + "");
			return;
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = "bl_" + targetX + "_bt_" + targetY;

		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					userId = rslt.data["l_" + targetX + "_t_" + targetY].tileUserId;
					if (rslt.data["l_" + targetX + "_t_" + targetY].cityName) targetCityName = rslt.data["l_" + targetX + "_t_" + targetY].cityName;
					else targetCityName = "---";
					if (userId != null && userId != 0) targetName = rslt.userInfo["u" + userId]["n"];
					for (i = 1; i <= Seed.cities.length; i++)
						if (Seed.cities[i - 1][0] == t.from.city.id) cityNumber = i;
					AtkOptions[cityNumber].push({
						what: "Attack",
						city: t.from.city.id,
						action: 4,
						targetX: targetX,
						targetY: targetY,
						targetCityName: targetCityName,
						targetName: targetName,
						tileLevel: rslt.data["l_" + targetX + "_t_" + targetY].tileLevel,
						tileType: rslt.data["l_" + targetX + "_t_" + targetY].tileType,
						misted: rslt.data["l_" + targetX + "_t_" + targetY].misted,
						1: document.getElementById('Unt1').value,
						2: document.getElementById('Unt2').value,
						3: document.getElementById('Unt3').value,
						4: document.getElementById('Unt4').value,
						5: document.getElementById('Unt5').value,
						6: document.getElementById('Unt6').value,
						7: document.getElementById('Unt7').value,
						8: document.getElementById('Unt8').value,
						9: document.getElementById('Unt9').value,
						10: document.getElementById('Unt10').value,
						11: document.getElementById('Unt11').value,
						12: document.getElementById('Unt12').value,
						13: document.getElementById('Unt13').value,
						14: document.getElementById('Unt14').value,
						15: document.getElementById('Unt15').value,
						16: document.getElementById('Unt16').value,
						r1: 0,
						r2: 0,
						r3: 0,
						r4: 0,
						r5: 0,
						gold: 0,
					});
					saveAtkOptions();
					t.PaintQueue();
					for (i = 1; i <= 16; i++) document.getElementById('Unt' + i).value = 0;
					document.getElementById('targetX').value = "";
					document.getElementById('targetY').value = "";
				}
			},
		});
	},

	CalcMax: function (i) {
		var t = Tabs.Attack;
		var othertroops = 0;
		var max = 0;
		id = i.substr(10);
		var rinfo = getRallypointInfo(t.from.city.id);
		t.maxsend = rinfo.maxMarchSize;
		for (i = 1; i <= 16; i++)
			if (id != i) othertroops += parseInt(document.getElementById('Unt' + i).value);
		if (othertroops < t.maxsend) max = (t.maxsend - othertroops);
		if (max > Seed.units["city" + t.from.city.id]["unt" + id]) max = Seed.units["city" + t.from.city.id]["unt" + id];
		document.getElementById('Unt' + id).value = Math.floor(max);
	},


	PaintQueue: function () {
		var t = Tabs.Attack;
		document.getElementById('AtkQueue').innerHTML = '<TABLE id=AtkShowQ align="center" width=95%></table>';
		for (var i = 1; i <= Seed.cities.length; i++) {
			CityQueue = AtkOptions[i];
			for (var y = 0; y < CityQueue.length; y++) {
				tag = "city" + i + "item" + y;
				t._addTab(CityQueue[y], tag, i, y);
			}
		}
		t._addTabHeader();
	},

	_addTab: function (action, k, city, item) {
		var t = Tabs.Attack;

		for (postcity in Seed.cities)
			if (Seed.cities[postcity][0] == action.city) logcity = Seed.cities[postcity][1];
		var troops = "<table>";
		var info = "";
		var type = "";
		for (i = 1; i <= 16; i++) {
			if (parseIntNan(action[i]) > 0 ) {
				troops += '<tr><td><img width=20 src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_30.jpg" title="'+uW.unitnamedesctranslated["unt" + i][0]+'"></td><td> ' + addCommas(parseIntNan(action[i])) + "</td></tr>";
			}
		}
		troops+="</table>";
		switch (parseInt(action.tileType)) {
		case 0:
			info = "Bog";
			break;
		case 10:
			info = "Grassland";
			break;
		case 11:
			info = "Lake";
			break;
		case 20:
			info = "Woods";
			break;
		case 30:
			info = "Hills";
			break;
		case 40:
			info = "Mountain";
			break;
		case 50:
			info = "Plain";
			break;
		case 51:
			if (action.targetCityName == null && !action.misted) info = "Barb Camp";
			else info = action.targetName;
			break;
		case 53:
			info = "Misted City";
			break;
		}
		var row = document.getElementById('AtkShowQ').insertRow(0);
		row.vAlign = 'middle';
		row.style.color = "black";
		row.insertCell(0).innerHTML = '<A title="' + culang.mainDelete + '" onclick="RemoveAtkQueue(' + city + ',' + item + ')"><img src=""/>';
		row.insertCell(1).innerHTML = logcity;
		row.insertCell(2).innerHTML = "<a href='javascript:void(0)' onclick='clickKoords(event)' class=''>(" + parseInt(action.targetX) + "," + parseInt(action.targetY) + ")</a>"; //coordLink(parseInt(action.targetX),parseInt(action.targetY));
		row.insertCell(3).innerHTML = info;
		row.insertCell(4).innerHTML = action.targetCityName;
		row.insertCell(5).innerHTML = action.tileLevel;
		row.insertCell(6).innerHTML = troops;
		row.insertCell(7).innerHTML = '<a class="button20" id="Details' + k + '"><span>' + culang.tabs_send_details + '</span></a>';
		document.getElementById('Details' + k).addEventListener('click', function () {
			t.DetailsPop(action, logcity, info);
		}, false);
	},

	_addTabHeader: function () {
		var t = Tabs.Attack;
		var row = document.getElementById('AtkShowQ').insertRow(0);
		row.vAlign = 'top';
		row.style.color = "black";
		row.insertCell(0).innerHTML = "&nbsp";
		row.insertCell(1).innerHTML = '<b>'+culang.tabs_send_fromcity+'</b>';
		row.insertCell(2).innerHTML = '<b>'+culang.tabs_send_coords+'</b>';
		row.insertCell(3).innerHTML = '<b>'+culang.mainTarget+'</b>';
		row.insertCell(4).innerHTML = '<b>'+culang.mainCity+'</b>';
		row.insertCell(5).innerHTML = '<b>Level</b>';
		row.insertCell(6).innerHTML = '<b>'+culang.mainTroops+'</b>';
		row.insertCell(7).innerHTML = '<b>'+culang.tabs_send_details+'</b>';
	},

	DetailsPop: function (action, logcity, info) {
		var t = Tabs.Attack;
		var m = '<TABLE id=pbMarch width=100% height=0% class=pdxTab>';
		m += '<TR><TD width="50px"></td><TD>' + culang.mainCastle + ' ' + logcity + '</td></tr>';
		m += '<TR><TD width="50px"></td><TD>' + culang.mainTarget + ' ' + info + '</td></tr>';
		m += '<TR><TD width="50px"></td><TD>' + culang.mainCity + ' ' + action.targetCityName + '</td></tr>';
		m += '<TR><TD width="50px"></td><TD>Level: ' + action.tileLevel + '</td></tr>';
		// m+= '<TR><TD width="50px"></td><TD>Coords: ' +  coordLink(parseInt(action.targetX),parseInt(action.targetY)) + '</td></tr></table><BR>';
		m += "<TR><TD width='50px'></td><TD>" + culang.tabs_send_coords + ": <a href='javascript:void(0)' onclick='clickKoords(event)' class='coordinateLink'>(" + parseInt(action.targetX) + "," + parseInt(action.targetY) + ")</a></td></tr></table><BR>";

		m += '<TABLE id=pbMarch width=100% height=0% class=pdxTab><TR>';
		for (i = 1; i <= 4; i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD width="75px">' + addCommas(parseIntNan(action[i])) + '</td>';
		m += '</tr><TR>';
		for (i = 5; i <= 8; i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD width="75px">' + addCommas(parseIntNan(action[i])) + '</td>';
		m += '</tr><TR>';
		for (i = 9; i <= 12; i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD width="75px">' + addCommas(parseIntNan(action[i])) + '</td>';
		m += '</tr><TR>';
		for (i = 13; i <= 16; i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg"></td><TD width="75px">' + addCommas(parseIntNan(action[i])) + '</td>';
		m += '</tr></table><BR>';
		var pop = new CPopup('giftHelp', 0, 0, 550, 410, true);
		pop.centerMe(mainPop.getMainDiv());
		pop.getMainDiv().innerHTML = m;
		pop.getTopDiv().innerHTML = '<DIV class="popupBanner">' + culang.tabs_send_pop_head_savedmarches + '</DIV>';
		pop.show(true);
	},

	ClickCitySelect: function (city) {
		var t = Tabs.Attack;
		for (i = 1; i <= 16; i++) document.getElementById('unit' + i).innerHTML = addCommas(Seed.units["city" + t.from.city.id]["unt" + i]);
	},

	RemoveQueue: function (city, item) {
		var t = Tabs.Attack;
		AtkOptions[city].splice(item, 1);
		t.PaintQueue();
		saveAtkOptions();
	},

	doMarch: function (cityID, i) {
		var t = Tabs.Attack;
		for (var y = 0; y < AtkOptions[i + 1].length; y++)
			if (AtkOptions[i + 1][y]["city"] == cityID) MarchQueue[i + 1].push(AtkOptions[i + 1][y]);
	},

	show: function () {
		var t = Tabs.Attack;
	},
	hide: function () {
		var t = Tabs.Attack;
	},
	onUnload: function () {},
}

//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/March.js">
//	
//	   KOC POWER - TABS MARCH											        
//	


Tabs.March = {
  tabOrder: TabOptions.toMarches,
  tabLabel: culang.tabLabelSendMarch,
  myDiv: null,
  cityID: null,
  rallypointlevel:null,
  maxsend:0,
  dist:0,
  ETAstr:null,
  ETAType:null,
  checkETA:null,
  knt:null,
  ETAstr:null,
  ETAType:null,
  checkETA:null,
  resources:["food","wood","stone","iron","aetherstone"],
  speed:["0,0","0,180","0,200","0,3000","0,300","0,275","0,250","1,1000","1,750","1,150","1,100","1,120","1,80","0,900","0,500","1,775"],

    init: function(div){
    	var t = Tabs.March;
        t.myDiv = div;
        uW.RemoveQueue = t.RemoveQueue;

        t.i931 = 0;
	    t.i932 = 0;
	    t.i55 = 0;
	    t.i57 = 0;
	    
	    if (Seed.items['i'+931]) t.i931 = Seed.items['i'+931];
	    if (Seed.items['i'+932]) t.i932 = Seed.items['i'+932];
	    if (Seed.items['i'+55]) t.i55 = Seed.items['i'+55];
	    if (Seed.items['i'+57]) t.i57 = Seed.items['i'+57];

      	var m = t.PaintContent();
      	t.myDiv.innerHTML = m;

      	if (t.i931 == 0) document.getElementById('AuraOfCommand').disabled = true; else document.getElementById('AuraOfCommand').disabled = false;
      	if (t.i932 == 0) document.getElementById('AuraOfConquest').disabled = true; else document.getElementById('AuraOfConquest').disabled = false;
      	if (t.i55 == 0) document.getElementById('GreenGriffin').disabled = true; else document.getElementById('GreenGriffin').disabled = false;
      	if (t.i57 == 0) document.getElementById('RedDragon').disabled = true; else document.getElementById('RedDragon').disabled = false;

      	t.from = new CdispCityPicker ('pbMfrom', document.getElementById('pbMcityFrom'), true, t.ClickCitySelect, 0);  
      	t.to = new CdispCityPicker ('pbMcityTo', document.getElementById ('pbMcityTo'), true, t.citySelNotify);
		t.to.bindToXYboxes(document.getElementById ('MtargetX'), document.getElementById ('MtargetY'));

      	for (i=1;i<=15;i++)  document.getElementById('M_Max'+i).addEventListener('click', function(){t.CalcMax(this.id);t.ETA();}, false);
        for (i=0;i<5;i++)  document.getElementById('M_R_Max'+i).addEventListener('click', function(){t.Calc_R_Max(this.id)}, false);
        for (i=1;i<=15;i++)  document.getElementById('M_Unt'+i).addEventListener('change', function(){t.ETA()}, false);	
        document.getElementById('MtargetX').addEventListener('change', function(){if (document.getElementById("MtargetX").value != "" && document.getElementById("MtargetY").value != "") document.getElementById('M_Dist'). innerHTML = "<b>"+culang.shortDistance+":</b> " + distance(t.from.city.x, t.from.city.y, document.getElementById("MtargetX").value, document.getElementById("MtargetY").value);}, false);
    	document.getElementById('MtargetY').addEventListener('change', function(){if (document.getElementById("MtargetX").value != "" && document.getElementById("MtargetY").value != "") document.getElementById('M_Dist'). innerHTML = "<b>"+culang.shortDistance+":</b> " + distance(t.from.city.x, t.from.city.y, document.getElementById("MtargetX").value, document.getElementById("MtargetY").value);}, false);
		document.getElementById('addToQueue').addEventListener ('click', t.GetCoords,false); 	
		document.getElementById('ManualMarch').addEventListener ('click', t.ManualMarch,false);
		document.getElementById('pbMarchType').addEventListener ('click', t.MarchType,false);
		document.getElementById('RedDragon').addEventListener ('click', t.PaintMarchSize,false);
		document.getElementById('AuraOfCommand').addEventListener ('click', t.PaintMarchSize,false);
		document.getElementById('AuraOfConquest').addEventListener ('click', t.PaintMarchSize,false);
		document.getElementById('GreenGriffin').addEventListener ('click', function(){if (document.getElementById('GreenGriffin').checked) document.getElementById('RedDragon').checked = false;t.ETA();},false);
		document.getElementById('RedDragon').addEventListener ('click', function(){if (document.getElementById('RedDragon').checked) document.getElementById('GreenGriffin').checked = false;t.ETA();},false);
        if (MarchOptions.Queue.length > 0) t.PaintQueue();
        t.PaintMarchSize(); 
        t.ClickCitySelect();  
        t.MarchType();
    },

    PaintContent : function (){
    	var t = Tabs.March;
    	var color = "black";
    	var m = '<DIV id=pbReinfMain class=pdxStat>'+culang.tabs_send_head+'</div><DIV id=MPresetCont></div>'; 
      	m += '<DIV id=pbReinfMain class=pdxStat>'+culang.tabs_send_head_settings+'</div><TABLE id=pireinforce width=80% height=0% class=pdxTab>';    
      	m += '<TR><TD><B><u>'+culang.mainCastle+'</u></b></td><TD> <SPAN id=pbMcityFrom></span></td></tr>';
      	m += '<TR><TD><B><u>'+culang.mainTarget+'</u></b></td><TD> <SPAN id=pbMcityTo></span></td><TD><INPUT id=MtargetX maxlength=3 type=text>&nbsp&nbsp&nbspY:&nbsp<INPUT id=MtargetY maxlength=3 type=text></td>';
      	m += '<TD><SPAN id=M_Dist><b>'+culang.shortDistance+':</b> <i>'+culang.shortNotAvailable+'</i></span></td><TD><SPAN id=M_ETA><b>'+culang.shortETA+':</b> <i>'+culang.shortNotAvailable+'</i></span></td></tr></table>';
    	m += '<TABLE id=pbMarch width=100% height=0% class=pdxTab><TR>';
     	for (i=1;i<=5;i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg"></td><TD><SPAN id=M_unit'+i+'></span></td>';
      	m+='</tr><TR>';
      	for (i=1;i<=5;i++) m += '<TD><INPUT id=M_Unt'+i+' type=text size=10 maxlength=10 value="0"><INPUT id=M_Max'+i+' type=submit class=pbButton value='+culang.buttonMax+'></td>';
      	m+='</tr><TR>';   	
      	for (i=6;i<=10;i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg"></td><TD><SPAN id=M_unit'+i+'></span></td>';
      	m+='</tr><TR>';
      	for (i=6;i<=10;i++) m += '<TD><INPUT id=M_Unt'+i+' type=text size=10 maxlength=10 value="0"><INPUT id=M_Max'+i+' type=submit class=pbButton value='+culang.buttonMax+'></td>';
      	m+='</tr><TR>';
      	for (i=11;i<=15;i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg"></td><TD><SPAN id=M_unit'+i+'></span></td>';
      	m+='</tr><TR>';
      	for (i=11;i<=15;i++) m += '<TD><INPUT id=M_Unt'+i+' type=text size=10 maxlength=10 value="0"><INPUT id=M_Max'+i+' type=submit class=pbButton value='+culang.buttonMax+'></td>';
      	m+='</tr><TR>';
      	for (i=0;i<5;i++) m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/'+t.resources[i]+'_30.png"></td><TD><SPAN id=M_recInfo'+i+'></span></td>';
      	m+='</tr><TR>';
        for (i=0;i<5;i++) m += '<TD><INPUT id=M_Recource'+i+' type=text size=10 maxlength=10 value="0"><INPUT id=M_R_Max'+i+' type=submit class=pbButton value='+culang.buttonMax+'></td>';

	    m += '</tr></table><BR><TABLE id=pbReinfETA width=90% height=0% align="center" class=pdxTab>';
	    m += '<TR align="center"><TD rowspan=2 width=150px><SELECT id="pbMarchType"><OPTION value=4>'+culang.mainAttack+'</option><OPTION value=3>'+culang.mainScout+'</option><OPTION value=5>'+culang.mainReassign+'</option><OPTION value=2>'+culang.mainReinforce+'</option></select></td>';
	    m += '<TD rowspan=2><SELECT id=M_Knight type=list></select></td>';
	    m += '<TD rowspan=2 width=100px><a class="button20" id=addToQueue><span>'+culang.tabs_send_settings_savemarch+'</span></a></td><TD rowspan=2 width=100px><a class="button20" id=ManualMarch><span>'+culang.tabs_send_settings_manualmarch+'</span></a></td>';
	    m += '<TD style="width:30px;text-align:right"><INPUT id=AuraOfCommand type=checkbox unchecked=true><TD rowspan=2 width=30px><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/931.jpg></td>';
	    m += '<TD style="width:30px;text-align:right"><INPUT id=AuraOfConquest type=checkbox unchecked=true><TD rowspan=2 width=30px><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/932.jpg></td>';
	    m += '<TD style="width:30px;text-align:right"><INPUT id=GreenGriffin type=checkbox unchecked=true><TD rowspan=2 width=30px><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/55.jpg></td>';
	    m += '<TD style="width:30px;text-align:right"><INPUT id=RedDragon type=checkbox unchecked=true><TD rowspan=2 width=30px><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/57.jpg></td>';

	    if (t.i931 == 0) color = "red"; else color = "black";
	    m+= '<TR align="center"><TD align=right><FONT color='+color+'>'+t.i931+'</font></td>';
	    if (t.i932 == 0) color = "red"; else color = "black";
	    m+= '<TD align=right><FONT color='+color+'>'+t.i932+'</font></td>'
	    if (t.i55 == 0) color = "red"; else color = "black";
	    m+= '<TD align=right><FONT color='+color+'>'+t.i55+'</font></td>'
	    if (t.i57 == 0) color = "red"; else color = "black";
	    m+= '<TD align=right><FONT color='+color+'>'+t.i57+'</font></td>'
	    m += '</tr></table>';
	    m+= '<DIV id=MarchInfo></div>';
	    m+= '<DIV id=pbReinfMain class=pdxStat>'+culang.tabs_send_pop_head_savedmarches+'</div><BR><BR><DIV id=M_Queue></div>';
	    return m;
    },

    ListKnights : function(){
       	var t = Tabs.March;
       	var knt = new Array();
       	for (k in Seed.knights['city' + t.from.city.id]){
       		if (Seed.knights['city' + t.from.city.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.from.city.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"] && Seed.leaders['city' + t.from.city.id]["politicsKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"] && Seed.leaders['city' + t.from.city.id]["combatKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"] && Seed.leaders['city' + t.from.city.id]["intelligenceKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"]){
       			knt.push ({
       				Name:   Seed.knights['city' + t.from.city.id][k]["knightName"],
       				Combat:	(parseInt(Seed.knights['city' + t.from.city.id][k]["combat"])+((Seed.knights['city' + t.from.city.id][k]["combatBoostExpireUnixtime"]>0)?(Math.floor(parseInt(Seed.knights['city' + t.from.city.id][k]["combat"])*0.25)):0)),
       				ID:		Seed.knights['city' + t.from.city.id][k]["knightId"],
       			});
       		}
       	}
       	knt = knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
      	document.getElementById('M_Knight').options.length=0;	
		if (document.getElementById('pbMarchType').value != 4) t.AddZeroKnight();
       	for (k in knt){
    			if (knt[k]["Name"] !=undefined){
	    			var o = document.createElement("option");
	    			o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
	    			o.value = knt[k]["ID"];
	    			document.getElementById("M_Knight").options.add(o);
    			}
    	}
    	if (document.getElementById('pbMarchType').value == 4) t.AddZeroKnight();
    },

    AddZeroKnight: function(){
    	var o = document.createElement("option");
		o.text = ''+culang.tabs_send_knight_select+'';
		o.value = 0;
		document.getElementById("M_Knight").options.add(o);
    },

    PaintMarchSize : function (){
    	var t = Tabs.March;
			var rinfo = getRallypointInfo(t.from.city.id);
			t.maxsend = rinfo.maxMarchSize;
			var Aura = 0;
    	if (document.getElementById('AuraOfCommand').checked) {t.maxsend = rinfo.maxMarchSize25; Aura = 25;}
    	if (document.getElementById('AuraOfConquest').checked) {t.maxsend = rinfo.maxMarchSize50;	Aura = 50;}
			var TR = uW.cm.ThroneController.effectBonus(66);
			if (TR > 150) TR = 150;
    	var m = '<b>'+culang.tabs_send_marchsize+'</b> ' + addCommas(Math.floor(t.maxsend)) + ' '+culang.tabs_send_marchsize2+' ' + TR + ''+culang.tabs_send_marchsize3+' ' + Aura + ''+culang.tabs_send_marchsize4+'';
    	document.getElementById('MPresetCont').innerHTML = m;
		},

    MarchType : function(){
    	var t = Tabs.March;  
    	if (document.getElementById('pbMarchType').value == 3) {
    		for (var i=1;i<=15;i++) if (i!=3) {
    			document.getElementById('M_Unt'+i).disabled = true;
    			document.getElementById('M_Unt'+i).value = 0;
    			document.getElementById('M_Max'+i).disabled = true;
    		} else if (Seed.units["city" + t.from.city.id]["unt"+i] ==0) {
    			document.getElementById('M_Unt'+i).disabled = true;
    			document.getElementById('M_Unt'+i).value = 0;
    			document.getElementById('M_Max'+i).disabled = true;
    		} else {
    			document.getElementById('M_Unt'+i).disabled = false;
	    		document.getElementById('M_Max'+i).disabled = false; 
    		}
    	} else for (var i=1;i<=15;i++) {
    		if (Seed.units["city" + t.from.city.id]["unt"+i] == 0) {
	    		document.getElementById('M_Unt'+i).disabled = true;
	    		document.getElementById('M_Unt'+i).value = 0;
	    		document.getElementById('M_Max'+i).disabled = true; 
	    	} else {
	    		document.getElementById('M_Unt'+i).disabled = false;
	    		document.getElementById('M_Max'+i).disabled = false; 
	    	}
    	}

    	if (document.getElementById('pbMarchType').value != 2) for (i=0;i<5;i++) {document.getElementById('M_Recource'+i).disabled = true;document.getElementById('M_R_Max'+i).disabled = true;}
    	else for (i=0;i<5;i++) {document.getElementById('M_Recource'+i).disabled = false;document.getElementById('M_R_Max'+i).disabled = false;}
    	t.ListKnights();
    },

    ShowWarning: function(msg,ok){
    	var t = Tabs.March;
    	if (ok) var color = "green";
    	 else var color = "red";
    	document.getElementById('MarchInfo').innerHTML = '<FONT color='+color+'><B>' + msg + '</b></font>';
    },

    ManualMarch : function (){
    	var t = Tabs.March;
    	var params = uW.Object.clone(uW.g_ajaxparams);
    	var total = 0;
		params.kid = document.getElementById("M_Knight").value;
		if (params.kid == 0 && document.getElementById('pbMarchType').value==4) {t.ShowWarning(''+culang.tabs_send_selknight+'',false);return;}
		params.cid=t.from.city.id;
    	params.type=document.getElementById('pbMarchType').value;
	    params.xcoord = document.getElementById('MtargetX').value;
	    params.ycoord = document.getElementById('MtargetY').value;
	    TroopsOK = true;
	    for (var i=1;i<=15;i++){
	    	TroopsInCity = Seed.units['city'+t.from.city.id]['unt'+i];
    		if (parseInt(TroopsInCity) < parseInt(document.getElementById('M_Unt'+i).value)) TroopsOK = false;
    		else if (parseInt(document.getElementById('M_Unt'+i).value) > 0) params['u'+i]=parseInt(document.getElementById('M_Unt'+i).value);
	    }
	    for (i=0;i<5;i++) params['r'+(i+1)] = document.getElementById('M_Recource'+i).value; 
	    if (!TroopsOK) return;

	    if (params.xcoord =="" || params.xcoord=="") {t.ShowWarning(""+culang.tabs_send_entercoords+"",false);return;}
	    for (i=1;i<=15;i++) total += parseInt(document.getElementById('M_Unt'+i).value);
	    if (total == 0) {t.ShowWarning(""+culang.tabs_send_send1trp+"",false);return;}
		if (total > t.maxsend) {t.ShowWarning(""+culang.tabs_send_wrongtraura+"",false);return;}

	    var items=new Array();
	    if (document.getElementById('AuraOfCommand').checked) items.push(931);
	    if (document.getElementById('AuraOfConquest').checked) items.push(932);
	    if (document.getElementById('GreenGriffin').checked) items.push(55);
	    if (document.getElementById('RedDragon').checked) items.push(57);
	    if (items.length > 0) params.items=items.join(","); 
	     
    	new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
              method: "post",
              parameters: params,
              loading: true,
              onSuccess: function (transport) {
                  var rslt = eval("(" + transport.responseText + ")");
                  if (rslt.ok) {
	                  var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
										var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
										var ut = uW.unixtime();
										var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
										for(i = 0; i <= unitsarr.length; i++){
											if(params["u"+i]){
												unitsarr[i] = params["u"+i];
											}
										}
										var resources=new Array();
										resources[0] = params.gold;
										for(i=1; i<=4; i++){
											resources[i] = params["r"+i];
										}
										var currentcityid = params.cid;
										uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
												 
										if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};	
										for(var i=0;i<items.length;i++){
											Seed.items["i"+items[i]]=parseInt(Seed.items["i"+items[i]])-1;
											uW.ksoItems[items[i]].subtract();
										}
	                  //t.myDiv.innerHTML = "";
	                  //t.init(t.myDiv);
	                  switch (parseInt(params.type)) {
											case 1: var type = "TRANSPORT";break;
											case 2: var type = "REINFORCE";break;
											case 3: var type = "SCOUT";break;
											case 4: var type = "ATTACK";break;
											case 5: var type = "REASSIGN";break;
										}
					  
				  
	                  msg = ''+culang.tabs_send_sendto+' ' + type + ' '+culang.tabs_send_sendto2+' <a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+params.xcoord+','+params.ycoord+')</a>';
	                  t.ShowWarning(msg,true);
	                  setTimeout(t.ShowWarning,5000,"",true)
	                  t.PaintMarchSize(); 
        			  t.ClickCitySelect();  
        			  t.MarchType();
                  } else {t.ShowWarning(""+culang.mainError+": "+ rslt.msg,false)}
              },
              onFailure: function () {}
      });     

    },

    Calc_R_Max : function(what){
    	var t = Tabs.March;
    	var otherResources = 0;
    	var maxload = 0;
    	var otherRes = 0;
    	id = what.substr(7);
		for (i=1;i<=15;i++) if (parseInt(document.getElementById('M_Unt'+i).value) > 0) maxload += getMaxLoad(i,parseInt(document.getElementById('M_Unt'+i).value));
		for (i=0;i<5;i++) if (id != i) otherRes += parseInt(document.getElementById('M_Recource' + i).value);
		maxload = maxload - otherRes;
		document.getElementById('M_Recource'+id).value = maxload;
    },

    CalcMax : function (i){
    	var t = Tabs.March;
			var rinfo = getRallypointInfo(t.from.city.id);
			t.maxsend = rinfo.maxMarchSize;
			var Aura = 0;
    	if (document.getElementById('AuraOfCommand').checked) {t.maxsend = rinfo.maxMarchSize25; Aura = 25;}
    	if (document.getElementById('AuraOfConquest').checked) {t.maxsend = rinfo.maxMarchSize50;	Aura = 50;}
    	var othertroops=0;
    	var max=0;
    	id = i.substr(5);			
    	for (i=1;i<=15;i++) if (id !=i) othertroops += parseInt(document.getElementById('M_Unt'+i).value);
    	if (othertroops < t.maxsend) max = (t.maxsend - othertroops);   	
    	if (max > Seed.units["city" + t.from.city.id]["unt"+id]) max = Seed.units["city" + t.from.city.id]["unt"+id];
    	document.getElementById('M_Unt'+id).value = Math.floor(max);
    },

    ETA : function (){
    	var t = Tabs.March;
    	var a = {};
    	for (i=1;i<=15;i++) a[i] = document.getElementById('M_Unt'+i).value;
    	var items = {};

    	if (document.getElementById('GreenGriffin').checked) items["55"] = true;
	     else if (document.getElementById('RedDragon').checked) items["57"] = true;
    	var dist = distance(t.from.city.x, t.from.city.y, document.getElementById("MtargetX").value, document.getElementById("MtargetY").value)
    	var ETA = marchTimeCalculator(a, false, items, t.from.city.id, document.getElementById('pbMarchType').value,dist);
    	document.getElementById('M_ETA').innerHTML = '<b>'+culang.shortETA+':</b> '+ETA;
    },

	GetCoords : function (){
	    var t= Tabs.March;
	    var targetName = "";
	    var targetCityName = "";
	    var total=0;
	    targetX = document.getElementById('MtargetX').value;
	    targetY = document.getElementById('MtargetY').value;
	    if (targetX =="" || targetY=="") {alert(""+culang.tabs_send_entercoords+"");return;}
	    for (i=1;i<=15;i++) total += parseInt(document.getElementById('M_Unt'+i).value);
	    if (total == 0) {alert(""+culang.tabs_send_send1trp+"");return;}
	    var params = uW.Object.clone(uW.g_ajaxparams);
    	params.blocks = "bl_" + targetX + "_bt_" + targetY;
	    
	    new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
      		method: "post",
      		parameters: params,
      		onSuccess: function (rslt) {
        		if (rslt.ok) {
        			if (rslt.data["l_"+targetX+"_t_"+targetY].tileType == 51) {
        				userId = rslt.data["l_"+targetX+"_t_"+targetY].tileUserId;
        				if (userId != null) targetName = rslt.userInfo["u" + userId]["n"];
        				targetCityName = rslt.data["l_"+targetX+"_t_"+targetY].cityName;
        			}
        			MarchOptions.Queue.push ({
        				what: 			"March",
        				city: 			t.from.city.id,
        				action: 		document.getElementById('pbMarchType').value,
        				targetX: 		targetX,
        				targetY: 		targetY,
        				tileType: 		rslt.data["l_"+targetX+"_t_"+targetY].tileType,
        				tileLevel: 		rslt.data["l_"+targetX+"_t_"+targetY].tileLevel,
        				targetCityName: targetCityName,
        				targetName: 	targetName,
        				cityNumber: 	rslt.data["l_"+targetX+"_t_"+targetY].cityNum,
        				1: 				document.getElementById('M_Unt1').value,
        				2: 				document.getElementById('M_Unt2').value,
        				3: 				document.getElementById('M_Unt3').value,
        				4: 				document.getElementById('M_Unt4').value,
        				5: 				document.getElementById('M_Unt5').value,
        				6: 				document.getElementById('M_Unt6').value,
        				7: 				document.getElementById('M_Unt7').value,
        				8: 				document.getElementById('M_Unt8').value,
        				9: 				document.getElementById('M_Unt9').value,
        				10: 			document.getElementById('M_Unt10').value,
        				11: 			document.getElementById('M_Unt11').value,
        				12: 			document.getElementById('M_Unt12').value,
        				13: 			document.getElementById('M_Unt13').value,
        				14: 			document.getElementById('M_Unt14').value,
        				15: 			document.getElementById('M_Unt15').value,	
        				r1: 			document.getElementById('M_Recource0').value,
        				r2: 			document.getElementById('M_Recource1').value,
        				r3: 			document.getElementById('M_Recource2').value,
        				r4: 			document.getElementById('M_Recource3').value,
        				r5: 			document.getElementById('M_Recource4').value
        			});
					t.PaintQueue();
					saveMarchOptions();
					for(i=1;i<=15;i++) document.getElementById('M_Unt'+i).value=0;
					document.getElementById('MtargetX').value="";
					document.getElementById('MtargetY').value="";
					Dashboard.ShowMarches();
        		}
      		},
    	});	
	},

PaintQueue : function (){
    var t= Tabs.March;
    document.getElementById('M_Queue').innerHTML = '<TABLE id=ShowQ class=pdxStat align="center" width=80%></table>';
    for (k=(MarchOptions.Queue.length-1);k>=0;k--) t._addTab(MarchOptions.Queue[k],k);  
    t._addTabHeader();
 },

 _addTab: function(action,k){
    var t = Tabs.March;
    for (postcity in Seed.cities) if (Seed.cities[postcity][0] == action.city) logcity = Seed.cities[postcity][1];
    var total = 0;
	var info = "";
	var type="";
	for (i=1;i<=15;i++) total += parseInt(action[i]);
	switch (parseInt(action.tileType)) {
		case 0: info = "Bog";break;
		case 10: info = "Grassland";break;
		case 11: info = "Lake";break;
		case 20: info = "Woods";break;
		case 30: info = "Hills";break;
		case 40: info = "Mountain";break;
		case 50: info = "Plain";break;
		case 51: 
			if (action.targetCityName == null && !action.misted) info = "Barb Camp";
				else info = action.targetName;
			break;
		case 53: info = "Misted City";break;
	}
	switch (parseInt(action.action)) {
		case 1: type = "TRANSPORT";break;
		case 2: type = "REINFORCE";break;
		case 3: type = "SCOUT";break;
		case 4: type = "ATTACK";break;
		case 5: type = "REASSIGN";break;
	}
    var row = document.getElementById('ShowQ').insertRow(0);
    row.vAlign = 'top';
    row.style.color = "black";
    row.insertCell(0).innerHTML ='<A title="'+culang.mainDelete+'" onclick="RemoveQueue('+ k +')"><img src=""/>';	  
    row.insertCell(1).innerHTML = logcity;
    row.insertCell(2).innerHTML = '<a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ parseInt(action.targetX) +','+ parseInt(action.targetY) +')</a>';
    row.insertCell(3).innerHTML = info;
    row.insertCell(4).innerHTML = action.targetCityName;
    row.insertCell(5).innerHTML = action.tileLevel;
    row.insertCell(6).innerHTML = addCommas(total);
    row.insertCell(7).innerHTML = '<a class="button20" id="Details' + k + '"><span>'+culang.tabs_send_details+'</span></a>&nbsp&nbsp&nbsp<a class="button20 ptButtonRed" id="doAction' + k + '"><span>'+ type+'</span></a>';
    document.getElementById('doAction' + k).addEventListener('click', function(){t.doMarch(action);}, false);
    document.getElementById('Details' + k).addEventListener('click', function(){t.DetailsPop(action,logcity,info);}, false);
},

_addTabHeader: function() {
    var t = Tabs.March;
    var row = document.getElementById('ShowQ').insertRow(0);
    row.vAlign = 'top';
    row.style.color = "black";
    row.insertCell(0).innerHTML = "&nbsp";
    row.insertCell(1).innerHTML = ""+culang.tabs_send_fromcity+"";
    row.insertCell(2).innerHTML = ""+culang.tabs_send_coords+"";
    row.insertCell(3).innerHTML = ""+culang.mainTarget+"";
    row.insertCell(4).innerHTML = ""+culang.mainCity+"";
    row.insertCell(5).innerHTML = "Level";
    row.insertCell(6).innerHTML = ""+culang.mainTroops+"";
    row.insertCell(7).innerHTML = ""+culang.mainAction+"";
},

DetailsPop : function (action,logcity,info){
	var t = Tabs.March;
	var m = '<TABLE id=pbMarch width=100% height=0% class=pdxTab>';
    m+= '<TR><TD width="50px"></td><TD'+culang.mainCastle+' ' + logcity + '</td></tr>';
    m+= '<TR><TD width="50px"></td><TD>'+culang.mainTarget+' ' + info + '</td></tr>';
    m+= '<TR><TD width="50px"></td><TD>'+culang.mainCity+' ' + action.targetCityName + '</td></tr>';
    m+= '<TR><TD width="50px"></td><TD>Level: ' + action.tileLevel + '</td></tr>';
	
    m+= '<TR><TD width="50px"></td><TD>'+culang.tabs_send_coords+': <a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ parseInt(action.targetX) +','+ parseInt(action.targetY) +')</a></td></tr></table><BR>';
    m += '<TABLE id=pbMarch width=100% height=0% class=pdxTab><TR>';
    for (i=1;i<=4;i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_50.jpg"></td><TD width="75px">'+ addCommas(action[i]) +'</td>';
    m+='</tr><TR>'; 
    for (i=5;i<=8;i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_50.jpg"></td><TD width="75px">'+ addCommas(action[i]) +'</td>';
    m+='</tr><TR>'; 
    for (i=9;i<=12;i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_50.jpg"></td><TD width="75px">'+ addCommas(action[i]) +'</td>';
    m+='</tr><TR>';
    for (i=13;i<=15;i++) m += '<TD width="51px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_50.jpg"></td><TD width="75px">'+ addCommas(action[i]) +'</td>';
    m+='</tr></table><BR>'; 
	m += '<TABLE id=pbMarch width=100% height=0% class=pdxTab><TR>';
    m+='<TD width="30px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/food_30.png"></td><TD width="100px">' + addCommas(action.r1) +'</td>';
	m+='<TD width="30px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/wood_30.png"></td><TD width="100px">' + addCommas(action.r2) +'</td>';
	m+='<TD width="30px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/stone_30.png"></td><TD width="100px">' + addCommas(action.r3) +'</td>';
	m+='<TD width="30px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/iron_30.png"></td><TD width="100px">' + addCommas(action.r4) +'</td>';
	m+='</tr></TR><TD width="30px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/aetherstone_30.png"></td><TD width="100px">' + addCommas(action.r5) +'</td>';
	m+='<TD width="30px"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/gold_30.png"></td><TD width="100px">' + addCommas(action.gold) +'</td>';
	m+='</tr></table>'; 	
    var pop = new CPopup ('giftHelp', 0, 0, 550, 410, true);
    pop.centerMe (mainPop.getMainDiv());  
    pop.getMainDiv().innerHTML = m;
    pop.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.tabs_send_pop_head_savedmarches+'</DIV>';
    pop.show (true);
  },


    
ClickCitySelect: function(city){
    var t = Tabs.March;  
    for (i=1;i<=15;i++) {
    	document.getElementById('M_unit'+i).innerHTML = addCommas(Seed.units["city" + t.from.city.id]["unt"+i]);
    	if (Seed.units["city" + t.from.city.id]["unt"+i] ==0) {
    		document.getElementById('M_Unt'+i).disabled = true;
    		document.getElementById('M_Unt'+i).value = 0;
    		document.getElementById('M_Max'+i).disabled = true;
    	}
    }
    for (i=0;i<=4;i++) {
    	var rec = 0;
    	if (i==4) rec = parseInt(Seed.resources["city" + t.from.city.id]['rec'+(i+1)][0]);
    	else rec = parseInt(Seed.resources["city" + t.from.city.id]['rec'+(i+1)][0]/3600);
    	document.getElementById('M_recInfo'+i).innerHTML = addCommas(Math.round(rec));	
    }
    if (document.getElementById("MtargetX").value != "" && document.getElementById("MtargetY").value != "") {
    	document.getElementById('M_Dist'). innerHTML = ""+culang.shortDistance+": " + distance(t.from.city.x, t.from.city.y, document.getElementById("MtargetX").value, document.getElementById("MtargetY").value);
    	t.ETA();
    }
    t.ListKnights();
    t.PaintMarchSize();
    t.MarchType();
},

RemoveQueue: function(id){
    var t = Tabs.March;
    MarchOptions.Queue.splice(id,1);
    t.PaintQueue();
	saveMarchOptions();
	Dashboard.ShowMarches();
},
             
getKnights : function(){
   var t = Tabs.March;
   t.knt = new Array();
   for (k in Seed.knights['city' + t.from.city.id]){
           if (Seed.knights['city' + t.from.city.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.from.city.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"] && Seed.leaders['city' + t.from.city.id]["politicsKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"] && Seed.leaders['city' + t.from.city.id]["combatKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"] && Seed.leaders['city' + t.from.city.id]["intelligenceKnightId"] != Seed.knights['city' + t.from.city.id][k]["knightId"]){
               t.knt.push ({
                   Name:   Seed.knights['city' + t.from.city.id][k]["knightName"],
                   Combat:    parseInt(Seed.knights['city' + t.from.city.id][k]["combat"]),
                   ID:        Seed.knights['city' + t.from.city.id][k]["knightId"],
               });
           }
   }
   t.knt = t.knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
},

    
    getRallypoint: function(cityId){
      var t = Tabs.March;
      for (var o in Seed.buildings[cityId]){
        var buildingType = parseInt(Seed.buildings[cityId][o][0]);
        var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
        if (buildingType == 12) t.rallypointlevel=parseInt(buildingLevel);
       }
     if(t.rallypointlevel == 11) t.rallypointlevel = 15;
     if(t.rallypointlevel == 12) t.rallypointlevel = 20;      
 	},

  
    doMarch: function(action){
        var t = Tabs.March;
        t.getKnights();
		if (t.knt.toSource() == "[]") return;
		var kid = t.knt[0].ID;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.cid=action.city;
        params.type=action.action;
        if (action.action == 4 || action.action == 5) params.kid=kid;
        else params.kid=0;
        params.xcoord = action.targetX;
        params.ycoord = action.targetY;
        params.u1=action["1"];
        params.u2=action["2"];
        params.u3=action["3"];
        params.u4=action["4"];
        params.u5=action["5"];
        params.u6=action["6"];
        params.u7=action["7"];
        params.u8=action["8"];
        params.u9=action["9"];
        params.u10=action["10"];
        params.u11=action["11"];
        params.u12=action["12"];
        params.u13=action["13"];
        params.u14=action["14"];
        params.u15=action["15"];
        if (action.gold) params.gold = action.gold;
      	if (action.r1) params.r1= action.r1;
      	if (action.r2) params.r2= action.r2;
      	if (action.r3) params.r3= action.r3;
      	if (action.r4) params.r4= action.r4;
      	if (action.r5) params.r5= action.r5;
        
        var total=0;
    	var max = 0;
    	t.getRallypoint("city" + action.city);
    	RallypointMax = (t.rallypointlevel * 10000);
    	var TR = uW.cm.ThroneController.effectBonus(66);
    	if (TR > 150) TR=150;
    	//t.maxsend = RallypointMax + ((RallypointMax / 100) * TR);
    	t.maxsend = RallypointMax + Math.round(RallypointMax * (TR / 100));
    	if (Seed.cityData.city[t.from.city.id].isPrestigeCity) {
    		switch(parseInt(Seed.cityData.city[t.from.city.id].prestigeInfo.prestigeLevel)){
    			case 1: t.maxsend = Math.round(t.maxsend * 1.50);break;
    			case 2: t.maxsend = Math.round(t.maxsend * 1.60);break;
    			case 3: t.maxsend = Math.round(t.maxsend * 1.65);break;
    		}
    	}
    	for (i=1;i<=15;i++) total += parseInt(params["u"+i]);
    	if (total > t.maxsend) {alert(""+culang.tabs_send_wrongtr+"");return;}
    	
          new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
                  method: "post",
                  parameters: params,
                  loading: true,
                  onSuccess: function (transport) {
	                  var rslt = eval("(" + transport.responseText + ")");
	                  if (rslt.ok) {
		                  	var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
												var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
												var ut = uW.unixtime();
												var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
												for(i = 0; i <= unitsarr.length; i++){
													if(params["u"+i]){
														unitsarr[i] = params["u"+i];
													}
												}
												var resources=new Array();
												resources[0] = params.gold;
												for(i=1; i<=4; i++){
													resources[i] = params["r"+i];
												}
												var currentcityid = params.cid;
												uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
														 
												if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
										} 
           
                  },
                  onFailure: function () {}
          });
               
    },
    
    
    show: function(){
        var t = Tabs.March;
        if (MarchOptions.Queue.length > 0) t.PaintQueue();
    },
    hide: function(){
        var t = Tabs.March;
    },
    onUnload: function(){
    },
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/AutoCraft.js">
//	
//	   KOC POWER - TABS AUTOCRAFT										        
//	


Tabs.AutoCraft = {
	tabOrder: TabOptions.toAutoCraft,
	tabLabel: culang.tabLabelAutoCraft,
	myDiv: null,
	timer: null,
	crafting: [],
	craftinfo : {},
	craftitems : {},
	myDiv: null,
	timer: null,
	timerStat: null,
	numcity :-1,
	wait:false,
	viewstats: null,
	options: {
		running: false,
		CraftingNb: {},
		CraftingNbC: {},
		throneCheck: false,
		throneSet: 1,
		SimpleItems: false,
		stats: {},
		UseSpeedups: false,
	},
	id: {},
	SpeedCity: 0,
	
	UseSpeedup: function() {
		var t = Tabs.AutoCraft;
		try {
		var now = unixTime();
		//RefreshSeed aktiv?
		if (RefreshingSeed) return;
		
		//Craftfunktion nicht aktiv?
		if (t.options.running == false) {
			return;
		}
		//Sollten Stundenglaeser verwendet werden?
		if (t.options.UseSpeedups == false) {
			return;
		}
		//Stadt durchzaehlen
		if (t.SpeedCity >= Cities.cities.length) t.SpeedCity = 0;
		var cityId = Cities.cities[t.SpeedCity].id;
		t.SpeedCity++;
		
		//Craftauftrag suchen
		var time = 0;
		var cid = 0;
		var qcon = Seed.queue_craft["city" + cityId];
		if (matTypeof(qcon)=='array' && qcon.length > 0) {
			if (parseIntNan(qcon[0].craftingEtaUnixTime) > now + 15) {
				time = 	parseIntNan(qcon[0].craftingEtaUnixTime) - now;
				cid = qcon[0].craftingId;
			}	else {
				//Stadt wechseln
				setTimeout(t.UseSpeedup, 250);
				return;
			}
		} else {
			//Stadt wechseln
			setTimeout(t.UseSpeedup, 250);
			return;
		}
		//Passende Sanduhr ermitteln
		var item = getSpeedup(time);
	
		//Keine passende Sanduhr
		if (item == 0) {
			//Stadt wechseln
			setTimeout(t.UseSpeedup, 250);
			return;
		}	
		//Speedup verwenden
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'Crafting';
		params.action = 'speedup';
		params.cityId = cityId;
		params.itemId = item;
		params.craftingId = cid;

		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (transport) {
				var rslt=eval("("+transport.responseText+")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				
					//Item aus Inventar entfernen
					Seed.items["i" + item] = parseInt(Seed.items["i" + item]) - 1;
					uW.ksoItems[item].subtract();
					//Suche des Bauauftrages
					var qloc = 0;		
					for (var i = 0; i < Seed.queue_craft["city" + cityId].length; i++) {
						if (parseInt(Seed.queue_craft["city" + cityId][i].craftingId) == parseInt(cid)) {
							qloc = i;
							break;
						}
					}
					//Zeit um Itemzeit reduzieren
					var timered = 0;
					var timeredarr = [60, 900, 3600, 9000, 28800, 54000, 86400, 216000, 0, 345600];			
					var utstart = parseInt(Seed.queue_craft["city" + cityId][qloc].craftingUnixTime);
					var uteta = parseInt(Seed.queue_craft["city" + cityId][qloc].craftingEtaUnixTime);
					timered = timeredarr[parseInt(item) - 1];
					Seed.queue_craft["city" + cityId][qloc].craftingUnixTime = utstart - timered;
					Seed.queue_craft["city" + cityId][qloc].craftingEtaUnixTime = uteta - timered;
					if (cityId == uW.currentcityid) uW.update_queue();
					//Logbucheintrag
					var rep = {
						'item' : uW.itemlist['i'+item].name,
						'city' : Cities.byID[cityId].name,
					};
					actionLog(culang.tabLabelAutoCraft,culang.craftUseSpeedupsOK.mreplace(rep));		
			
			},
		});

		//naechste Stadt
		} catch (ex) {
					alert('21644/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
		setTimeout(t.UseSpeedup, 5000);
	},

	readOptions: function() {
		var t = Tabs.AutoCraft;
		var a = getServerId();
		var u = getMyUserId();
		var s = GM_getValue("CraftingData_"+a+"_"+u);
		if(s != null){
			opts = JSON2.parse(s);
			for(k in opts){
				t.options[k] = opts[k];
			}
		}
	},
	saveOptions: function() {
		var t = Tabs.AutoCraft;
		var a = getServerId();
		var u = getMyUserId();
		setTimeout(function(){
			GM_setValue("CraftingData_"+a+"_"+u, JSON2.stringify(t.options));
		},0)
	},

	init: function(div){
		var t = Tabs.AutoCraft;
		t.myDiv = div;
		t.readOptions();
		var m = '<DIV id=pbBuildDivF class=pdxStat>'+culang.craftHead+'</div><TABLE width=100% height=0% class=pdxTab><TR>';
		if (t.options.running == false) {
			m += '<TD style="text-align: center;"><INPUT id=pbCraftRunning type=submit value="'+culang.craftButton+' = '+culang.buttonOFF+'"></td>';
		} else {
			m += '<TD style="text-align: center;"><INPUT id=pbCraftRunning type=submit value="'+culang.craftButton+' = '+culang.buttonON+'"></td>';
			t.timer=setInterval(t.Start,8000);
			setTimeout(t.UseSpeedup, 9000);
		}
		m += "<td style='text-align: center;'><input id=pbCraftStats type=submit value='"+culang.craftStats+"'></td>";
		m += "<td><input type=checkbox id=pbCraftThroneCheck "+ (t.options.throneCheck?'CHECKED':'') +"> " + culang.mainCraftOnlyThroneSet;
		m += " <SELECT id=pbCraftThroneSet>"; 
		for (i=1;i<=Seed.throne.slotNum;i++){
			m += '<option value="'+i+'">'+i+'</option>';
		}
		m +='</select><br>';
		m += "<input type=checkbox id=pbCraftSimpleItems "+ (t.options.SimpleItems?'CHECKED':'') +"> " + culang.mainCraftSimpleItems;
		m += "<br><input type=checkbox id=pbCraftUseSpeedup "+ (t.options.UseSpeedups?'CHECKED':'') +"> " + culang.craftUseSpeedups;
		m +='</td>';
		m +='<td id="pbCraftSpeed" style="text-align:center;"></td>';
		m += '</tr></table>';
		m += '<DIV id=pbBuildDivQ class=pdxStat>'+culang.craftHeadStats+'</div><span id="KsCraftStat"></span>';
		m += '<DIV id=pbBuildDivQ class=pdxStat>'+culang.craftHeadSettings+'</div><div style="max-height:700px;overflow-y:auto"><TABLE width=100% height=0% class=pdxTab style="border-collapse:collapse;"><TR>';

		m += "<td colspan=2><b><u>"+culang.mainItems+"</u></b></td>";
		m += "<td style='text-align:center;'><b><u>"+culang.mainInventory+"</u></b></td>";
		m += "<td style='text-align:center;'><b><u>"+uW.g_js_strings.commonstr.cities+"</u></b></td>";
		m += "<td><b><u>"+culang.mainAmount+"</u></b></td>";
		m += "<td width=10 style='border-right: 1px solid black;'>&nbsp;</td><td width=10>&nbsp;</td>";
		m += "<td colspan=2><b><u>"+culang.mainItems+"</u></b></td>";
		m += "<td style='text-align:center;'><b><u>"+culang.mainInventory+"</u></b></td>";
		m += "<td style='text-align:center;'><b><u>"+uW.g_js_strings.commonstr.cities+"</u></b></td>";
		m += "<td><b><u>"+culang.mainAmount+"</u></b></td></tr>";
		m += "<tr>";

		var z=0;
		for(var i=0; i < uW.recipelist[1].length; i++){
			var h = parseInt(uW.recipelist[1][i].output_item_id);
			t.craftitems[uW.recipelist[1][i].recipe_id] = h;
			t.craftinfo[h] = {};
			t.craftinfo[h].recipe_id = uW.recipelist[1][i].recipe_id;
			t.craftinfo[h].category = uW.recipelist[1][i].category;
			t.craftinfo[h].input = uW.recipelist[1][i].input;
			t.craftinfo[h].requirements = uW.recipelist[1][i].requirements;
			t.craftinfo[h].consolation = uW.recipelist[1][i].consolation_item_id;
			var title = addCommas(t.craftinfo[h].input.resources['1']) + " " + uW.g_js_strings.commonstr.aetherstones + "\n";
			if (t.craftinfo[h].input.items.length == undefined) {
				for (j in t.craftinfo[h].input.items) {
					var anz = parseInt(t.craftinfo[h].input.items[j]);			
					title += anz + " " + uW.itemlist["i"+j].name + "\n";
				}
			}
			title += uW.buildingcost.bdg20[0] + ' Level ' + t.craftinfo[h].requirements.building;
			m += "<td width='27'><img title='"+title+"' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td>";
			m += "<td>"+uW.itemlist["i"+h].name+"</td>";
			m += "<td id='KsCraft_nbi_"+h+"' style='text-align:center;font-weight:bold;'>"+parseIntNan(Seed.items["i"+h])+"</td>";
			if (!t.options.stats[h]) t.options.stats[h] = {'e':0,'f':0,'s':0}; //Error, Fail, Success
			if (!t.options.CraftingNbC[h]) t.options.CraftingNbC[h] = {0:"y", 1:"y", 2:"y", 3:"y", 4:"y", 5:"y", 6:"y", 7:"y"};
			m += "<td>";
			for(j=0; j<Cities.numCities; j++) {
				if (t.options.CraftingNbC[h][j] == "y") {
					m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: green; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
				} else {
					m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: red; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
				}
			}
			m += "</td>";
			m += "<td><input style='text-align:center;' type=text size=4 id='KsCraft_nb_"+h+"' value='"+ parseIntNan(t.options.CraftingNb[h]) +"'></td>";
			if ((z+1)%2 == 1) m += "<td style='border-right:1px solid black;'></td><td></td>";
			if ((z+1)%2 == 0) m += "</tr><tr>";
			z++;
		}
		for(var i=0; i < uW.recipelist[3].length; i++){
			var h = parseInt(uW.recipelist[3][i].output_item_id);
			t.craftitems[uW.recipelist[3][i].recipe_id] = h;
			t.craftinfo[h] = {};
			t.craftinfo[h].recipe_id = uW.recipelist[3][i].recipe_id;
			t.craftinfo[h].category = uW.recipelist[3][i].category;
			t.craftinfo[h].input = uW.recipelist[3][i].input;
			t.craftinfo[h].requirements = uW.recipelist[3][i].requirements;
			t.craftinfo[h].consolation = uW.recipelist[3][i].consolation_item_id;
			var title = addCommas(t.craftinfo[h].input.resources['1']) + " " + uW.g_js_strings.commonstr.aetherstones + "\n";
			if (t.craftinfo[h].input.items.length == undefined) {
				for (j in t.craftinfo[h].input.items) {
					var anz = parseInt(t.craftinfo[h].input.items[j]);			
					title += anz + " " + uW.itemlist["i"+j].name + "\n";
				}
			}
			title += uW.buildingcost.bdg20[0] + ' Level ' + t.craftinfo[h].requirements.building;
			m += "<td width='27'><img title='"+title+"' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td>";
			m += "<td>"+uW.itemlist["i"+h].name+"</center></td>";
			m += "<td id='KsCraft_nbi_"+h+"'  style='text-align:center;font-weight:bold;'>"+parseIntNan(Seed.items["i"+h])+"</td>";
			if (!t.options.stats[h]) t.options.stats[h] = {'e':0,'f':0,'s':0}; //Error, Fail, Success
			if (!t.options.CraftingNbC[h]) t.options.CraftingNbC[h] = {0:"y", 1:"y", 2:"y", 3:"y", 4:"y", 5:"y", 6:"y", 7:"y"};
			m += "<td>";
			for(j=0; j<Cities.numCities; j++) {
				if (t.options.CraftingNbC[h][j] == "y") {
					m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: green; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
				} else {
					m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: red; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
				}
			}
			m += "</td>";
			m += "<td><input style='text-align:center;' type=text size=4 id='KsCraft_nb_"+h+"' value='"+ parseIntNan(t.options.CraftingNb[h]) +"'></td>";
			if ((z+1)%2 == 1) m += "<td style='border-right:1px solid black;'></td><td></td>";
			if ((z+1)%2 == 0) m += "</tr><tr>";
			z++;
		}
		m+="</tr></table></div>";
		t.myDiv.innerHTML = m;
		
		t.id["pbCraftStats"] = ById("pbCraftStats");
		t.id["pbCraftStats"].addEventListener ('click', function (){t.viewCraftStats()}, false);
		t.id["KsCraftStat"] = ById("KsCraftStat");
		t.id["pbCraftThroneCheck"] = ById("pbCraftThroneCheck");
		t.id["pbCraftThroneCheck"].addEventListener ('click', function(e){
			t.options.throneCheck = e.target.checked;
			t.saveOptions();
		}, false);		
		t.id["pbCraftThroneSet"] = ById("pbCraftThroneSet");
		t.id["pbCraftThroneSet"].value = t.options.throneSet;
		t.id["pbCraftThroneSet"].addEventListener ('change',function(e){
			t.options.throneSet = this.value;
			t.saveOptions();
		}, false);		
		t.id["pbCraftSimpleItems"] = ById("pbCraftSimpleItems");
		t.id["pbCraftSimpleItems"].addEventListener ('click', function(e){
			t.options.SimpleItems = e.target.checked;
			t.saveOptions();
		}, false);	
		t.id["pbCraftSpeed"] = ById("pbCraftSpeed");
		t.id["pbCraftRunning"] = ById("pbCraftRunning");
		t.id["pbCraftRunning"].addEventListener ('click', function (){t.toggleCraftStateRunning()}, false);
		t.id["pbCraftUseSpeedup"] = ById("pbCraftUseSpeedup");
		t.id["pbCraftUseSpeedup"].addEventListener ('click', function(e){
			t.options.UseSpeedups = e.target.checked;
			t.saveOptions();
		}, false);	
		for(var h in t.craftinfo) {
			t.id["KsCraft_nbi_"+h] = ById("KsCraft_nbi_"+h);
			t.id["KsCraft_nb_" +h] = ById("KsCraft_nb_" +h);
			t.id["KsCraft_nb_" +h].addEventListener ('keyup', function () {
				var item = ById(this.id);
				item.value = parseIntNan(item.value);
				t.saveCraftState();
			}, false);
			for(j=0; j<Cities.numCities; j++) {
				t.id["KsCraft_nbc_"+j+"_"+h] = ById("KsCraft_nbc_"+j+"_"+h);
				t.id["KsCraft_nbc_"+j+"_"+h].addEventListener ('click', function (){
					var item = ById(this.id);
					var info = this.id.split("_");
					var h = info[3];
					var j = info[2];
					if (!t.options.CraftingNbC[h][j]) t.options.CraftingNbC[h][j] = "y";
					if (t.options.CraftingNbC[h][j] == "y") {
						t.options.CraftingNbC[h][j] = "n";
						item.style.backgroundColor = "red";
					} else {
						t.options.CraftingNbC[h][j] = "y";
						item.style.backgroundColor = "green";
					}
					t.saveCraftState();
				}, false);
			}
		}
		t.updateStat();
	},
	
	viewCraftStats: function() {
		var t = Tabs.AutoCraft;
		if(t.viewstats == null)
			t.viewstats = new CPopup ('pbviewcraftstats', 0, 0, 900, 750, true);
		t.viewstats.centerMe (mainPop.getMainDiv());
		var m= '<TABLE width=100% class=pdxTab style="border-collapse:collapse;">';
		m += "<tr>";
		m += "<td colspan=2><b><u>"+culang.mainItems+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccess+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsFail+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccessrate+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsError+"</b></u></td>";
		m += "<td style='border-right:1px solid black; width:10px;'>&nbsp;</td><td style='width:10px;'>&nbsp;</td>";
		m += "<td colspan=2><b><u>"+culang.mainItems+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccess+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsFail+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccessrate+"</b></u></td>";
		m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsError+"</b></u></td>";
		m += "</tr>";
		var z=0;
		for(var h in t.craftinfo) {
			z++;
			if (z%2 == 1) m += "<tr>";
			m += "<td width='27'><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td>";
			m += "<td>"+uW.itemlist["i"+h].name+"</td>";
			m += "<td style='text-align:center;'>"+addCommas(t.options.stats[h].s)+"</td>";
			m += "<td style='text-align:center;'>"+addCommas(t.options.stats[h].f)+"</td>";
			if (t.options.stats[h].s + t.options.stats[h].f == 0) var rate = 0;
			else var rate = Math.round(t.options.stats[h].s * 10000 / (t.options.stats[h].s + t.options.stats[h].f))/100;
			m += "<td style='text-align:center;'><b>"+rate+"%</b></td>";
			m += "<td style='text-align:center;'>"+addCommas(t.options.stats[h].e)+"</td>";
			if (z%2 == 1) m += "<td style='border-right:1px solid black;'></td><td></td>";
			if (z%2 == 0) m += "</tr>";
		}
		m+='</table>';
		m+='<br><div style="text-align:center;"><input type="submit" value="'+culang.craftStatsDelete+'" id="pbCraftStatReset"></div>';
		t.viewstats.getMainDiv().innerHTML = m;
		t.viewstats.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.viewCraftStats+'</div>';
		ById("pbCraftStatReset").addEventListener ('click', function (){
			for(var h in t.craftinfo) {
				t.options.stats[h] = {'e':0,'f':0,'s':0};
			}
			t.saveOptions();
			t.viewCraftStats();
		}, false);
		t.viewstats.show(true);
	},
	
	updateStat: function() {
		var t = Tabs.AutoCraft;
		var rownum = 0;
		function _row (name, row, noTotal, typee){
			if (rownum++ % 2)
				style = '';
			else
				style = ' style = "background: #e8e8e8"';
			var tot = 0;
			var m = [];
			m.push ('<TR style="background: #fff" align=right');
			m.push (style);
			m.push ('><TD');
			m.push (style);
			m.push ('><B>');
			m.push (name);
			m.push ('</td>');
			if (noTotal){
				m.push ('<TD');
				m.push (style);
				m.push ('>&nbsp;</td>');
			} else {
				for (i=0; i<row.length; i++)
					tot += row[i];
				m.push ('<TD style="background: #ffc">');
				if (tot<0) {
					m.push ("<SPAN class=boldRed>"+addCommas(tot)+"</span>");
				} else {
					m.push (addCommas(tot));
				}
				m.push ('</td>');
			}
			for (i=0; i<row.length; i++){
				m.push ('<TD');
				m.push (style);
				m.push ('>');
				if (row[i]<5000) {
					m.push ("<SPAN class=boldRed>"+addCommas(row[i])+"</span>");
				} else {
					m.push (addCommas(row[i]));
				}
				m.push ('</td>');
			}

			m.push ('</tr>');
			return m.join('');
		}

		clearTimeout(t.timerStat);
		var str="<TABLE class=pdxTab cellpadding=0 cellspacing=0><TR  align=center><TD width=55 align=center></td><TD width=88 style='background: #ffc; font-size:150%' align=center><SPAN class=shadowCaps>"+culang.mainTotal+"</SPAN></td>";
		for(i=0; i<Cities.numCities; i++) {
			cityID = 'city'+ Cities.cities[i].id;
			str += "<TD width=81><SPAN class=shadowCaps>"+ Cities.cities[i].name.substring(0,10) +"</SPAN></td>";
		}
		str+= '</tr>';
		rows = [];
		var now = unixTime();
		rows[0] = [];
		for(i=0; i<Cities.numCities; i++) {
			cityID = 'city'+ Cities.cities[i].id;
			rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
		}
		for (r=1; r<6; r++){
			rows[r] = [];
			for(i=0; i<Cities.numCities; i++) {
				cityID = 'city'+ Cities.cities[i].id;
				if (r==5)
					rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
				else
					rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
			}
		}
		str += _row ('<img height=18 src="'+IMGastone30+'">', rows[5], false, 0);
		str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/3.jpg title="'+culang.mainCrafting+'"></b></td><td>&nbsp;</td>';
		for(i=0; i<Cities.numCities; i++) {
			var totTime = 0;
			if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
				var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
				var totTime = 0;
				totTime = q.craftingEtaUnixTime - now;
				if (totTime < 0)
					totTime = 0;
				if (getCityBuilding(Cities.cities[i].id,20).count>0 && totTime == 0)
					affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
				else
					affuichage = timestr(totTime);
				str +="<td><span>"+ affuichage + "</span></td>";
			} else {
				affuichage = timestr(totTime);
				if (getCityBuilding(Cities.cities[i].id,20).count>0)
					affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
				str +="<td><span>"+affuichage+"</span></td>";
			}
		}
		str +="</tr>";
		
		//Bilder
		str +='<tr style="background: #e8e8e8" align=right><td>&nbsp;</td><td>&nbsp;</td>';
		for(i=0; i<Cities.numCities; i++) {
			if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
				var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
				var h = t.craftitems[q.recipeId];
				var totTime = 0;
				totTime = q.craftingEtaUnixTime - now;
				if (totTime < 0) totTime = 0;
				if (totTime == 0) {
					str +="<td>&nbsp;</td>";
				} else {
					str +="<td align=right><img title='"+uW.itemlist["i"+h].name+"' width='40' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg'></td>";
				}
			} else {
				str +="<td>&nbsp;</td>";
			}
		}
		str +="</tr></table>";
		t.id["KsCraftStat"].innerHTML=str;
		
		//Inventar
		for(var h in t.craftinfo) {
			t.id["KsCraft_nbi_"+h].innerHTML = parseIntNan(Seed.items["i"+h]);
		}

		//Throne
		var craftspeed = uW.cm.ThroneController.effectBonus(81);
		if (craftspeed > 200) {
			t.id["pbCraftSpeed"].innerHTML = '<b style="font-size:14px;">' +craftspeed + '% (max. 200%)</b><br>'+uW.g_js_strings.throneRoom.effectName_81;
		} else {
			t.id["pbCraftSpeed"].innerHTML = '<b style="font-size:14px;">' +craftspeed + '%</b><br>'+uW.g_js_strings.throneRoom.effectName_81;
		}

		if (t.options.throneCheck && Seed.throne.activeSlot != t.options.throneSet) {
			t.id["pbCraftSpeed"].style.backgroundColor = "maroon";
			t.id["pbCraftSpeed"].style.color = "white";
			t.id["pbCraftSpeed"].title = culang.falseThroneSet;
		} else {
			t.id["pbCraftSpeed"].style.backgroundColor = "white";
			t.id["pbCraftSpeed"].style.color = "black";
			t.id["pbCraftSpeed"].title = "";
		}
		
		t.timerStat = setTimeout(function() { t.updateStat(); }, 5000);
	},
	updateCraftnb : function() {
		var t = Tabs.AutoCraft;
		for(var h in t.craftinfo) {
			t.id["KsCraft_nb_"+h].value = parseIntNan(t.options.CraftingNb[h]) ;
		}
	},
	saveCraftState : function() {
		var t = Tabs.AutoCraft;
		for(var h in t.craftinfo) {
			t.options.CraftingNb[h] = parseIntNan(t.id["KsCraft_nb_"+h].value);
		}
		t.saveOptions();
	},
	toggleCraftStateRunning: function(){
		var t = Tabs.AutoCraft;
		obj = t.id['pbCraftRunning'];
		if (t.options.running == true) {
			t.options.running = false;
			t.saveCraftState();
			if (obj) obj.value = culang.craftButton+" = "+culang.buttonOFF;
			clearInterval(t.timer);
		} else {
			t.options.running = true;
			t.saveCraftState();
			if (obj) obj.value = culang.craftButton+" = "+culang.buttonON;
			t.timer=setInterval(t.Start,8000);
			setTimeout(t.UseSpeedup, 9000);
			t.Start();
		}
		t.updateCraftnb();
	},
	Start: function() {
		var t = Tabs.AutoCraft;
		if(!t.options.running) {
			clearInterval(t.timer);
			return;
		}
		//RefreshSeed aktiv?
		if (RefreshingSeed) {
			setTimeout(function() { t.Start(); }, 2000);
			return;
		}
		if (t.numcity<Cities.numCities-1) {
			t.numcity++;
		} else {
			t.numcity=0;
		}
		var c=t.numcity;
		var cityId=Cities.cities[c].id;
		
		//Kein Fay-Turm?
		var fay = getCityBuilding(cityId,20);		
		var ret=fay.count;
		if (ret==0) {
			setTimeout(function() { t.Start(); }, 2000);
			return;
		}
		
		//Mindestens 2500 Aethersteine?
		var aether = parseIntNan(Seed.resources["city" + cityId]['rec5'][0]);
		if (aether<2500) {
			setTimeout(function() { t.Start(); }, 2000);
			return;
		}	
		
		//Wird gerade ein Teil gebaut?
		var i=Seed.queue_craft["city"+cityId];
		if(i.length>0) {
			var q=i[0];
			var totTime = 0;
			var now = unixTime();
			totTime = parseInt(q.craftingEtaUnixTime) + 3 - now;
			if (totTime > 0) {
				setTimeout(function() { t.Start(); }, 2000);
				return;
			}
		}		
		
		//Craftliste auslesen
		var tableau = [];
		for(var d in t.options.CraftingNb) {
			if (parseIntNan(t.options.CraftingNb[d])>0) {
				//Itemdaten
				var itemId = d;
				var recipeId = t.craftinfo[itemId].recipe_id;
				var category = t.craftinfo[itemId].category;
				var input = t.craftinfo[itemId].input;
				var requirements = t.craftinfo[itemId].requirements;
					
				//Level des Fay-Towers?
				if (parseInt(fay.maxLevel) < parseInt(requirements.building)) {
					continue;
				}
			
				//Genug Aethersteine?
				if (aether < parseInt(input.resources['1'])) {
					continue;
				}
				
				//Genug Items vorhanden?
				if (input.items.length == undefined) {
					var next = false;
					for (i in input.items) {
						var anz = parseInt(input.items[i]);			
						if (!Seed.items['i'+i]) {
							next = true;
						}
						if (Seed.items['i'+i] < anz) {
							next = true;
						}
					}
					if (next == true) continue;
				}

				//Falsches Throne-Set?
				if (t.options.throneCheck && Seed.throne.activeSlot != t.options.throneSet) {
					//Einfaches Item?
					if(t.options.SimpleItems && (itemId == 3000 || itemId == 3001 || itemId == 3003 || itemId == 3007 || itemId == 3008 || itemId == 3009)) {
						//Einfache Items werden gecraftet
					} else {
						continue;
					}
				}
				
				//Item in dieser Stadt erlaubt?
				if (t.options.CraftingNbC[itemId][c] == "n") {
					continue;
				}
				
				//Item in List aufnehmen
				tableau.push(d);
			}
		}

		//Liste lehr?
		if (tableau.length == 0) {
			setTimeout(function() { t.Start(); }, 2000);
			return;
		}

		//Craftauftrag per Zufall
		var itemId = tableau[Math.floor(Math.random()*tableau.length)];
		var recipeId = t.craftinfo[itemId].recipe_id;
		var category = t.craftinfo[itemId].category;
		var input = t.craftinfo[itemId].input;
		var requirements = t.craftinfo[itemId].requirements;
		
		//Alles scheint OK
		if (!t.wait) {
			t.wait = true;
			t.CraftingItem(cityId,  itemId, recipeId, category);
		}
	},
	CraftingItem: function (currentcity, itemId, recipeId,category) {
		var t = Tabs.AutoCraft;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.action="craft";
		params.ctrl="Crafting";
		params.cityId=currentcity;
		params.insurance=false;
		params.itemId=itemId;
		params.recipeId=recipeId;
		params.categoryId=category;
		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, { method: "post", parameters: params,loading: true,
			onSuccess: function (transport) {
				t.wait = false;
				var o=eval("("+transport.responseText+")");
				if (o.updateSeed) { try {uW.update_seed(o.updateSeed);} catch (e) {} }
				if(o.ok===true){
					if (o.status=="error") {
						actionLog(culang.mainCrafting, culang.mainError + ": <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name + ' - <span class=boldRed>'+ o.errorMessage + '</span>'); //15.10.2012 Bommel
						t.options.stats[itemId].e++;
						t.saveOptions();
					} else if(o.status=="failure"){
						actionLog(culang.mainCrafting, culang.mainFailedAttempt + ": <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name ); //15.10.2012 Bommel
						t.options.stats[itemId].f++;
						t.saveOptions();
						//Items und Aether abziehen
						var input = t.craftinfo[itemId].input;
						var consolation = t.craftinfo[itemId].consolation;
						Seed.resources["city" + currentcity]['rec5'][0] = Seed.resources["city" + currentcity]['rec5'][0] - parseInt(input.resources['1']);
						if (input.items.length == undefined) {
							for (i in input.items) {
								var anz = parseInt(input.items[i]);
								Seed.items['i'+i] = Seed.items['i'+i] - anz;
								uW.ksoItems[i].subtract(anz);
								if (Seed.items['i'+i] < 0) {
									Seed.items['i'+i] = 0;
								}
							}
						}
						//Erstattung bei Fehler
						if (consolation != 0) {
							Seed.items['i'+consolation] = Seed.items['i'+consolation] + 1;
							uW.ksoItems[consolation].add(1);
						}
						t.updateCraftnb();
					} else if (o.status=="success"){
						actionLog(culang.mainCrafting, culang.mainSuccessfulAttempt + ": <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name ); //15.10.2012 Bommel
						t.options.stats[itemId].s++;
						t.saveOptions();
						t.options.CraftingNb[itemId] =  t.options.CraftingNb[itemId] - 1;
						Seed.queue_craft["city"+currentcity]=[];
						var n={};
						n.recipeId=recipeId;
						n.craftingUnixTime=o.time.startTime;
						n.craftingEtaUnixTime=o.time.endTime;
						n.craftingId=o.craftingId;
						n.categoryId=null;
						n.recipeIndex=null;
						Seed.queue_craft["city"+currentcity].push(n);
						//Items und Aether abziehen
						var input = t.craftinfo[itemId].input;
						var consolation = t.craftinfo[itemId].consolation;
						Seed.resources["city" + currentcity]['rec5'][0] = Seed.resources["city" + currentcity]['rec5'][0] - parseInt(input.resources['1']);
						if (input.items.length == undefined) {
							for (i in input.items) {
								var anz = parseInt(input.items[i]);
								Seed.items['i'+i] = Seed.items['i'+i] - anz;
								uW.ksoItems[i].subtract(anz);
								if (Seed.items['i'+i] < 0) {
									Seed.items['i'+i] = 0;
								}
							}
						}
						t.updateCraftnb();
					}
				}
			},
			onFailure: function () {  
				t.wait = false;
				actionLog(culang.mainCrafting, culang.mainFatalAjaxError + ":  <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name ); //15.10.2012 Bommel
			}
		});
	},
	show : function (){
		var t = Tabs.AutoCraft;
		clearTimeout(t.timerStat);
		t.updateStat();
	},
	hide: function(){
		var t = Tabs.AutoCraft;
		clearTimeout(t.timerStat);
	},
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Vip.js">
//	
//	   KOC POWER - TABS VIP STUFF										        
//	
// if(seed.player.userid == ) { 
// comming soon...
// }
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Options.js">
//	
//	   KOC POWER - TABS OPTIONS										        
//	


Tabs.Options = {
	tabOrder: TabOptions.toOptions,
	tabLabel: culang.tabLabelOptions,
	cont : null,
	state : null,
	fixAvailable : {},
	soundRepeatTimer : null,
	soundStopTimer : null,
	secondTimer : null,
	soundPlaying : false,
	maxEntries: 300,
	last250 : [],
	Data: {Options: {},GlobalOptions: {},Colors: {},ThroneOptions: {},CrestOptions: {},TrainOptions: {},ReassignRoutes: {},TransportOptions: {},TransportState: {},AtkOptions: {},DFOptions: {},ApothecaryOptions: {},FarmOptions: {},MarchOptions: {}},
  
	show : function (){
		var t = Tabs.Options;
	},

	stopSoundAlerts : function (){
		var t = Tabs.Options;
		obj = ById('optionsSoundStop');
		t.mss.stop (1);
		clearTimeout (t.soundStopTimer);
		clearTimeout (t.soundRepeatTimer);
		ById('optionsSoundStop').disabled = true;
		Options.alertSound.alarmActive = false;
		Options.alertSound.expireTime = 0;
		if (ById('botowertab')) ById('botowertab').style.display="none";
	},
	e_soundFileLoaded : function (){
		var t = Tabs.Options;
		if (t.mss.err) 
			ById('optionsLoadSWF').innerHTML = ''+culang.optionsLoadingsounderror+'';
		else
			ById('optionsLoadSWF').innerHTML = ''+culang.optionsChargement+'';
	},
	playSound : function (doRepeats){
		var t = Tabs.Options;
		ById('optionsSoundStop').disabled = false;
		clearTimeout (t.soundStopTimer);
		clearTimeout (t.soundRepeatTimer);
		t.mss.play();
		t.soundStopTimer = setTimeout (function(){t.mss.stop(); t.e_soundFinished()}, Options.alertSound.playLength*1000);
		if (doRepeats && Options.alertSound.repeat)
			t.soundRepeatTimer = setTimeout (function (){t.playSound(true)}, Options.alertSound.repeatDelay*60000);
		else
			Options.alertSound.alarmActive = false;
	},
	e_soundFinished : function (){
		var t = Tabs.Options;
		if (!Options.alertSound.alarmActive){
			ById('optionsSoundStop').disabled = true;
		}
	},
	soundTheAlert : function (m){
		var t = Tabs.Options;
		Options.alertSound.alarmActive = true;
		t.playSound(true);
	},


	hide : function (){
		var t = Tabs.Options;
	},
	togOpt : function (checkboxId, optionName, callEnable, callIsAvailable){
		var t = Tabs.Options;
		var checkbox = ById(checkboxId);

		if (callIsAvailable && callIsAvailable()==false){
			checkbox.disabled = true;
			return;
		}
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, callEnable).handler, false);
		function eventToggle (checkboxId, optionName, callOnChange){
			this.handler = handler;
			var optName = optionName;
			var callback = callOnChange;
			function handler(event){
				Options[optionName] = this.checked;
				saveOptions();
				if (callback != null)
					callback (this.checked);
			}
		}
	},


	init : function (div){
		var t = Tabs.Options;
		t.cont = div;
		uW.KsSaveCategorys = t.saveCategorys;
		if (Options.DeleteTimerMinute===undefined) Options.DeleteTimerMinute=5;
		if (Options.NewTabURL==undefined) Options.NewTabURL=homePage;
		if (Options.alertConfig.throneSet == undefined) Options.alertConfig.throneSet = 1;
		if (Options.alertConfig.throneSetRet == undefined) Options.alertConfig.throneSetRet = 1;
		if (Options.alertConfig.returnThroneMin == undefined) Options.alertConfig.returnThroneMin = 60;
		
		if (Options.URLson1.substr(Options.URLson1.length-4,4) == '.mp3') {
			Options.URLson1 = 'https://koc-power-pdx.googlecode.com/files/sonar.ogg';
		}
		if (Options.URLson2.substr(Options.URLson2.length-4,4) == '.mp3') {
			Options.URLson2 = 'https://koc-power-pdx.googlecode.com/files/alarm.ogg';
		}
		if (Options.URLson4.substr(Options.URLson4.length-4,4) == '.mp3') {
			Options.URLson4 = 'https://koc-power-pdx.googlecode.com/files/ding.ogg';
		}
		if (Options.URLson5.substr(Options.URLson5.length-4,4) == '.mp3') {
			Options.URLson5 = 'https://koc-power-pdx.googlecode.com/files/slap.ogg';
		}
		if (Options.URLson6.substr(Options.URLson6.length-4,4) == '.mp3') {
			Options.URLson6 = 'https://koc-power-pdx.googlecode.com/files/cartoon.ogg';
		}
		if (Options.alertSound.soundUrl.substr(Options.alertSound.soundUrl.length-4,4) == '.mp3') {
			Options.alertSound.soundUrl = DEFAULT_ALERT_SOUND_URL;
		}
		if (Options.soundURLF1.substr(Options.soundURLF1.length-4,4) == '.mp3') {
			Options.soundURLF1 = 'https://koc-power-pdx.googlecode.com/files/siren.ogg';
		}
		if (Options.soundURLF2.substr(Options.soundURLF2.length-4,4) == '.mp3') {
			Options.soundURLF2 = 'https://koc-power-pdx.googlecode.com/files/horn.ogg';
		}
		if (Options.soundURLF3.substr(Options.soundURLF3.length-4,4) == '.mp3') {
			Options.soundURLF3 = 'https://koc-power-pdx.googlecode.com/files/gunshot.ogg';
		}
		//Standardsounds checken
		if (Options.URLson1ST != 0 && Options.URLson1ST != 1) Options.URLson1ST = 1;
		if (Options.URLson2ST != 0 && Options.URLson2ST != 1) Options.URLson2ST = 1;
		if (Options.URLson4ST != 0 && Options.URLson4ST != 1) Options.URLson4ST = 1;
		if (Options.URLson5ST != 0 && Options.URLson5ST != 1) Options.URLson5ST = 1;
		if (Options.URLson6ST != 0 && Options.URLson6ST != 1) Options.URLson6ST = 1;
		if (Options.URLsonF1ST != 0 && Options.URLsonF1ST != 1) Options.URLsonF1ST = 1;
		if (Options.URLsonF2ST != 0 && Options.URLsonF2ST != 1) Options.URLsonF2ST = 1;
		if (Options.URLsonF3ST != 0 && Options.URLsonF3ST != 1) Options.URLsonF3ST = 1;
		if (Options.alertSound.soundUrlST != 0 && Options.alertSound.soundUrlST != 1) Options.alertSound.soundUrlST = 1;
		
		setTimeout(function() {
			AddTowerTab(' <img height="50" width="50" src="'+IMGSirene+'" title="'+culang.optionsStopSound+'"> ', t.stopSoundAlerts, 'botowertab');
		}, 1000);

		var chat = ById('kocmain_bottom').childNodes[1];
		if (chat) {
			var channel_input = nHtml.FindByXPath(chat,".//div[contains(@class,'mod_comm_forum')]");
			var ab = document.createElement('a');
			ab.className="mod_comm_set";
			channel_input.appendChild(ab);
			ab.innerHTML=""+culang.mainSmileys+"";
			ab.addEventListener ('click', function() {
				t.EmoHelp();
			},false);
			if (chat && Options.pdxLangFlag) {
			var cd = document.createElement('a');
			cd.className="mod_comm_flag";
			channel_input.appendChild(cd);	
			cd.innerHTML='<img height=16 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="'+culang.KsRunningLanguage+'">';
			cd.addEventListener ('click', function() {
				// t.EmoHelp();
			},false);
		}
		if (chat && Options.pdxHyperlinks) {
                        var cd = document.createElement('a');
                        cd.className="mod_comm_links";
                        channel_input.appendChild(cd);    
                        cd.innerHTML='<a href="#" onclick="document.getElementById(\'pdxInfoBoxShow\').style.display=(document.getElementById(\'pdxInfoBoxShow\').style.display== \'block\')?\'none\':\'block\';"><img src="'+IMGksMini+'" alt="KoC Scripts" width="16" height="16" border="0" title="'+culang.optionsHyperlinksButtonTitle+'"> </a>\
                        <DIV id="pdxInfoBoxShow" style="display:none;">\
                        <div class=pdxInfoBox>\
                        <a href="http://koc-power-all.webs.com/" target="_blank"><img src="'+IMGpdxTeam+'" alt="KoC Scripts" width="32" height="32" border="0" title="'+culang.KsInfoBoxHomePageNote+'"></a>\
                        <a href="http://koc-power-all.webs.com/apps/forums/" target="_blank"><img src="'+IMGteamLink+'" alt="KS Team" width="32" height="32" border="0" title="'+culang.KsInfoBoxTeamNote+'"></a>\
                        <a href="http://www.facebook.com/groups/TheEliteFew/" target="_blank"><img src="'+IMGdevGroup+'" alt="KS DevGroup" width="32" height="24" border="0" title="'+culang.KsInfoBoxDevGroupNote+'"></a>\
                        <a href="http://koc-power-all.webs.com/apps/profile/" target="_blank"><img src="'+IMGFBGroup+'" alt="Facebook Groups" width="32" height="32" border="0" title="'+culang.KsInfoBoxFacebookNote+'"></a>\
                        <a href="http://code.google.com/p/mad-hatters-magic-elite/" target="_blank"><img src="'+IMGgooglecode+'" alt="googlecode" width="32" height="32" border="0" title="'+culang.KsInfoBoxGCNote+'"></a>\
                        <a href="http://code.google.com/p/mad-hatters-magic-elite/issues/entry?show=review&former=sourcelist" target="_blank"><img src="'+IMGuserscripts+'" alt="Userscripts" width="32" height="32" border="0" title="'+culang.KsInfoBoxUserscriptsNote+'"></a>\
                        <a href="http://code.google.com/p/mad-hatters-magic-elite/issues/entry" target="_blank"><img src="'+IMGreport+'" alt="Report" width="32" height="32" border="0" title="'+culang.KsInfoBoxReportNote+'"></a>\
                        <a href="http://userscripts.org" target="_blank"><img src="'+IMGreview+'" alt="Review" width="32" height="32" border="0" title="'+culang.KsInfoBoxReviewNote+'"></a>\
                        <a href="http://www.mozilla.org/firefox/" target="_blank"><img src="'+IMGfirefox+'" alt="Firefox" width="32" height="32" border="0" title="'+culang.KsInfoBoxFirefoxNote+'"></a>\
                        <a href="https://addons.mozilla.org/de/firefox/addon/greasemonkey/" target="_blank"><img src="'+IMGgreasemonkey+'" alt="Greasemonkey" width="32" height="32" border="0" title="'+culang.KsInfoBoxGreasemonkeyNote+'"></a>\
                        <a href="https://addons.mozilla.org/de/firefox/addon/scriptish/" target="_blank"><img src="'+IMGscriptish+'" alt="Scriptish" width="32" height="32" border="0" title="'+culang.KsInfoBoxScriptishNote+'"></a>\
                        <a href="http://www.java.com/de/download/installed.jsp" target="_blank"><img src="'+IMGjava+'" alt="Java" width="32" height="32" border="0" title="'+culang.KsInfoBoxJavaNote+'"></a>\
                        <a href="http://www.adobe.com/de/software/flash/about/" target="_blank"><img src="'+IMGflash+'" alt="FlashPlayer" width="32" height="32" border="0" title="'+culang.KsInfoBoxFlashNote+'"> </a>\
                        <a href="http://www.4loot.com/?id=264098&src=em" target="_blank">  <img src="'+IMG4loot+'" alt="4Loot" width="30" height="30" border="0" title="'+culang.KsInfoBox4LootNote+'"> </a>\
                        </div>\
                        </div>';

			cd.addEventListener ('click', function() {
				// t.EmoHelp();
			},false);
		}

		} try {
			var html = '<DIV style="margin-top:5px; max-height:'+(Options.HauteurBoite-45)+'px; overflow:auto;">';
			
			/* powerLangOptions*/
			html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerLangOptions\');">'+culang.optionsHeadLanguage+'</a></div>';
			html += '<DIV id="powerLangOptions" style="display:'+Options["powerLangOptions"]+';">';
			html += '<TABLE class=pdxTab>\
			<TR><TD>&nbsp;</td><TD><B>'+culang.mainLangpacks+'</B>: <select id=pbLang '+(LangOptions.culang==0?'DISABLED':'')+'/>\
			<option value=0 >-- '+culang.mainSelect+' --</option>';
			for (var i in LangOptions.langpacks) {
				if(i == LangOptions.culang)
					html += '<option value="'+i+'" selected="selected">'+i+'</option>'; // Load Previous langpack Selection
				else
					html += '<option value="'+i+'">'+i+'</option>';
			}
			html += '</select><sup><b> '+culang.mainVersion+'</b>: <span class=boldRed>'+LangpackVersion+'</span></sup><br>\
			<INPUT id=pbupdatelanglist type=submit value='+langpack.buttonUpdate+'>\
			<sup><span class=boldRed><u>'+culang.mainImportant+'</u></span>:</sup> <span class=helpText>'+ culang.optionsLangpackNote+'</span></td>\
			<TD colspan="2"><a href="http://kocscripts.com" target="_blank" title="'+culang.optionsVisitKS+'"><img height="20" src="'+IMGpdxTeam+'"></a><sup><b><u>KoC Power - Multilang</u></b><img height=16 width=16 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="Du Benutz zur Zeit die Deutsche version vergiss nicht das Spiel selbst auch auf die gleiche Sprache einszustellen!"></sup><BR><sup>'+culang.optionsKsRunning+' "<a href="'+KsScriptPage+'" target="_blank" title="'+culang.optionsKsRunningNote+' '+KsScriptRunning+' '+culang.optionsKsRunningNote2+'">'+KsScriptRunning+'</a>" </sup> <b>'+culang.mainVersion+'</b>: <span class=boldRed>'+Version+' <a target="_blank" href="'+KsInstallLink+'" title="'+culang.ksInstallLatestNote+'"></span> <img height="16" src="'+IMGlatestVersion+'"><BR></a><sup>'+KsLatestVersion+'</sup></td></tr>\
			<TR><TD colspan="2"><strong>'+culang.optionsChangelogFiles+'</strong></td></tr></table></div>';

			/* powerTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerTabOptions\');">'+culang.optionsHeadMulti+'</a></div>';
				html += '<DIV id="powerTabOptions" style="display:'+Options["powerTabOptions"]+';">';
				html += '<TABLE class=pdxTab>\
				<TR><TD width=5%><INPUT id=ptAllowWinMove type=checkbox /></td><TD width=27%>'+culang.optionsWinDragDrop+'</td>\
				<TR><TD><INPUT id=pbEveryEnable type=checkbox /></td><TD>'+culang.optionsAutoRefreshIntervall+' <INPUT id=pbeverymins type=text size=2 maxlength=3 \> '+culang.optionsAutoRefreshIntervall2+' </td>\
				<TR><TD><INPUT id=pbRefreshSeed type=checkbox /></td><TD>'+culang.optionsAutoRefreshSeedIntervall+' <INPUT id=pbRefreshSeedInterval type=text size=2 maxlength=3 \> '+culang.optionsAutoRefreshSeedIntervall2+' </td>\
				<TR><TD><INPUT id=KsgmtClock type=checkbox '+ (Options.gmtClock?'CHECKED ':'') +'/></td><TD> '+culang.optionsGMTClock+' </td><TD></td></tr>\
				<TR><TD><INPUT id=KsWatchEnable type=checkbox '+ (GlobalOptions.pbWatchdog?'CHECKED ':'') +'/></td><TD>'+culang.optionsRefreshIfInaktive+'</td></tr>\
				<TR><TD><INPUT id=togDeleteButtons type=checkbox '+ (Options.deleteButtons?'CHECKED ':'') +'/></td><TD>'+culang.delPromoButtons+'</td></tr>\
				<TR><TD><INPUT id=togmerlinClose type=checkbox '+ (Options.merlinClose?'CHECKED ':'') +'/></td><TD>'+culang.merlinClose+'</td></tr>\
				<TR><TD><INPUT id=KsSummonToggle type=checkbox /></td><TD>'+culang.optionsHideSummoningCircle+'</td></tr>\
				<TR><TD><INPUT id=pbTresureChestFB type=checkbox /></td><TD>'+culang.TreasureChestPostFB+'</td></tr>\
				<TR><TD><INPUT id=pbsendmeaway type=checkbox '+ (GlobalOptions.pbNoMoreKabam?'CHECKED ':'')+'/></td><TD>'+culang.optionsAwayOnKabam+'</td></tr>\
				<TR><TD><INPUT id=togMultiBrowser type=checkbox '+ (Options.MultiBrowser?'CHECKED ':'') +'/></td><TD>'+culang.MultiBrowser+'</td></tr>\
				<TR><TD><INPUT id=togWWclick type=checkbox '+ (Options.WWclick?'CHECKED ':'') +'/></td><TD>'+culang.optionsMultiBrowserOverride+' CLICK</td></tr>\
				<TR><TD><INPUT id=togEnableButtler type=checkbox '+ (Options.enableButtler?'CHECKED ':'') +'/></td><TD colspan=3>'+culang.optionsEnableButtler+'</tr>\
				<TR><TD><INPUT id=togKsInfoBox type=checkbox /></td><TD colspan=3>'+culang.optionsInfoBox+'</td></tr>\
				<TR><TD><INPUT id=togEnableBrowserBG type=checkbox '+ (GlobalOptions.enableBrowserBG?'CHECKED ':'') +'/></td><td><span title="'+culang.optionsBrowserBGNote+'">'+ htmlSelector({backCol:''+culang.optionsBrowserBGColor+'', backImg:''+culang.optionsBrowserBGImage+'' }, GlobalOptions.backStyle,'id=KsBackSelector') +'</span> - '+culang.optionsBrowserBGImageURL+' <INPUT id=KsBackgroundImage type=text size=14 maxlength=1000 value="'+GlobalOptions.bgImg+'" title="'+culang.optionsBrowserBGImageNote+'">  '+culang.optionsBrowserBGorColor+' <INPUT id=KsBackgroundColor type=text size=7 maxlength=7 value="'+GlobalOptions.bgCol+'" title="'+culang.optionsBrowserBGColorNote+'"> <td></tr>';
				var citySelect = '<SELECT id=pcalertHQ name=pcalertHQ><option value="">-- '+culang.mainSelect+' --</option>';
				var couleur="";
				for (var c=0; c<Cities.numCities; c++) {
					aCity = Cities.cities[c].id;
					aVisuCity = Cities.cities[c].name + ' '+Cities.cities[c].x + ','+ Cities.cities[c].y+' ';
					citySelect += '<option value=\''+ aCity +'\' '+ (Options.alertConfig.hq==aCity?'SELECTED ':'') +'>'+aVisuCity+'</option>';
				}
				citySelect += '</select>';
				html +='<TR><td></td><TD align=left>'+culang.optionsMoreSelectHQ+':&nbsp;'+ citySelect +'</td></tr>\
				<TR><TD><INPUT id=togSelQG type=checkbox /></td><TD>'+culang.optionsMoreOpenHQ+' </td></tr>\
				<TR><TD><INPUT id=pbGoldEnable type=checkbox /></td><TD>'+culang.optionsMoreAutoGold+' <INPUT id=pbgoldLimit type=text size=2 maxlength=3>'+culang.optionsMoreAutoGold2+'</td></tr>\
				<TR><TD><INPUT id=togAttackPicker type=checkbox /></td><TD>'+culang.optionsMoreCityButtons+' ('+culang.optionsMoreCityButtons2+')  </td></tr>\
				<TR><TD><INPUT id=togmovementopen type=checkbox /></td><TD>'+culang.optionsmovementopen+'</td></tr>\
				<TR><TD><INPUT id=togEnhanceMsging type=checkbox /></td><TD>'+culang.optionsMoreMessage+'</td></tr>\
				<TR><TD></td><TD colspan=2>'+culang.options_rallypoint_keep+' <INPUT id=togKsRPClip type=text size=1 maxlength=1> '+culang.options_rallypoint_keep2+' (Global)</td></tr>\
				</table></div>';
			}

			/* Speedup Options */
			if (true) {
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'speedupOptions\');">'+culang.optionsHeadSpeedup+'</a></div>';
				html += '<DIV id="speedupOptions" style="display:'+Options["speedupOptions"]+';">';
				html += '<TABLE class=pdxTab>';
				for (var i=1; i<=10; i++) {
					if (i==9) continue;
					html += '<tr><td><img width=30 src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/'+i+'.jpg"></td>';
					html += '<td><input type=checkbox id=pbusespeedup'+i+'></td><td> <b>'+uW.itemlist['i'+i].name+'</b></td>';
					html += '<td> '+uW.itemlist['i'+i].description+'</td></tr>';
				}
				html += '</table></div>';
			}
			/* dashboardTabOptions */
			if(true){
					html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'dashboardTabOptions\');" title="Dashboard">'+culang.options_dashboard_head+'</a></div>';
					html += '<DIV id="dashboardTabOptions" style="display:'+Options["dashboardTabOptions"]+';">';
					var left = '<TABLE id=pbDashOpts width=100% class=pdxTab><TR>';
					left += '<TR><TD colspan=2>'+culang.options_dashboard_reswaring+'</td></tr>';
					left += '<TR><TD style="width:50px;"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/food_30.png"></td><TD><INPUT id=pbFoodWarning size=13 maxLength=12 type=text value='+DashboardOptions.foodLevel+'></td></tr>';
					left += '<TR><TD style="width:50px;"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/wood_30.png"></td><TD><INPUT id=pbWoodWarning size=13 maxLength=12 type=text value='+DashboardOptions.woodLevel+'></td></tr>';
					left += '<TR><TD style="width:50px;"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/stone_30.png"></td><TD><INPUT id=pbStoneWarning size=13 maxLength=12 type=text value='+DashboardOptions.stoneLevel+'></td></tr>';
					left += '<TR><TD style="width:50px;"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/iron_30.png"></td><TD><INPUT id=pbOreWarning size=13 maxLength=12 type=text value='+DashboardOptions.oreLevel+'></td></tr>';
					left += '<TR><TD style="width:50px;"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/aetherstone_30.png"><TD><INPUT id=pbAStoneWarning size=8 maxLength=7 type=text value='+DashboardOptions.astoneLevel+'></td></tr></table>';
					var right = '<TABLE id=pbDashOptsSel width=100% class=pdxTab>';
					right += '<TR><TD colspan=2>'+culang.options_dashboard_display+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=togKsShowStatus type=checkbox '+(DashboardOptions.showMultiNote?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_multi+'</td></tr>';
					right += '<TR style="display:none;"><TD colspan=3><INPUT id=pbShowThrone type=checkbox '+(DashboardOptions.showThrone?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_trpreset+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowRP type=checkbox '+(DashboardOptions.showRP?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_rps+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowStatus type=checkbox '+(DashboardOptions.showStatus?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_cds+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowTroops type=checkbox '+(DashboardOptions.showTroops?'CHECKED':'')+'>&nbsp; '+culang.mainTroops+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowTower type=checkbox '+(DashboardOptions.showTower?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_tower+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowWarnings type=checkbox '+(DashboardOptions.showWarnings?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_alerts+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowLog type=checkbox '+(DashboardOptions.showLog?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_5logitems+'</td></tr>';
					right += '<TR><TD colspan=3><INPUT id=pbShowMarches type=checkbox '+(DashboardOptions.showMarches?'CHECKED':'')+'>&nbsp; '+culang.options_dashboard_display_marches+'</td></tr>';
					right +='</table>';
					html += '<TABLE id=dbMain width=100% class=pdxTab><TD>'+left+'</td><TD>'+right+'</td></table>';
					html += '</div>';
			}
			
			/* tabsTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'tabsTabOptions\');">'+culang.optionsHeadTabs+'</a></div>';
				html += '<DIV id="tabsTabOptions" style="display:'+Options["tabsTabOptions"]+';">';
				html += '<TABLE class=pdxTab>\
				<TR><TD><INPUT id=togPDXMenuLeft type=checkbox /></td><TD colspan=3>'+culang.optionsPowerMenuLeft+'</td></tr>\
				<TR><TD><INPUT id=KsNewTab type=checkbox /></td><TD colspan=3>'+culang.optionsUserTab+': '+culang.mainURL+': <input type=text size=20 value="'+Options.NewTabURL+'" id=KsNewTabURL> '+culang.optionsTabName+': <input type=text size=10 maxlength=12 id=KsNewTabName value="'+Options.NewTabName+'"></td></tr>\
				<TR><TD><INPUT id=KsIdHomeTab type=checkbox /></td><TD colspan=3>'+culang.optionsKsTab+'</tr></table>';
				html += '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'tabsTabOrderOptions\').style.display=(document.getElementById(\'tabsTabOrderOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadTabsOrder+'</a> (POWER)</div>';
				html += '<DIV id="tabsTabOrderOptions" style="display:none;">';
				html += '<TABLE class=pdxTab>\
				<tr><td width="12"><INPUT id=KsToOverview type=text size=2 maxlength=2></td><td>'+culang.tabLabelOverview+'</td></tr>\
				<tr><td><INPUT id=KsToReports type=text size=2 maxlength=2></td><td>'+culang.mainReports+'</td></tr>\
				<tr><td><INPUT id=KsToMarches type=text size=2 maxlength=2></td><td>'+culang.tabLabelMarch+'</td></tr>\
				<tr><td><INPUT id=KsToSendMarches type=text size=2 maxlength=2></td><td>'+culang.tabLabelSendMarch+'</td></tr>\
				<tr><td><INPUT id=KsToTrain type=text size=2 maxlength=2></td><td>'+culang.tabLabelTrain+'</td></tr>\
				<tr><td><INPUT id=KsToAutoTrain type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoTrain+'</td></tr>\
				<tr><td><INPUT id=KsToPopControl type=text size=2 maxlength=2></td><td>'+culang.tabLabelPopControl+'</td></tr>\
				<tr><td><INPUT id=KsToThroneStuff type=text size=2 maxlength=2></td><td>'+culang.tabLabelThroneStuff+'</td></tr>\
				<tr><td><INPUT id=KsToSearch type=text size=2 maxlength=2></td><td>'+culang.tabLabelSearch+'</td></tr>\
				<tr><td><INPUT id=KsToTurboSearch type=text size=2 maxlength=2></td><td>'+culang.tabLabelTurboSearch+'</td></tr>\
				<tr><td><INPUT id=KsToPlayer type=text size=2 maxlength=2></td><td>'+culang.mainPlayer+'</td></tr>\
				<tr><td><INPUT id=KsToBuild type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoBuild+'</td></tr>\
				<tr><td><INPUT id=KsToTransport type=text size=2 maxlength=2></td><td>'+culang.mainTransport+'</td></tr>\
				<tr><td><INPUT id=KsToReassign type=text size=2 maxlength=2></td><td>'+culang.mainReassign+'</td></tr>\
				<tr><td><INPUT id=KsToAutoCraft type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoCraft+'</td></tr>\
				<tr><td><INPUT id=KsToFarm type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoFarm+'</td></tr>\
				<tr><td><INPUT id=KsToCrest type=text size=2 maxlength=2></td><td>'+culang.tabLabelCrest+'</td></tr>\
				<tr><td><INPUT id=KsToDarkForest type=text size=2 maxlength=2></td><td>'+culang.mainDarkForest+'</td></tr>\
				<tr><td><INPUT id=KsToAttackTab type=text size=2 maxlength=2></td><td>'+culang.mainAttack+'</td></tr>\
				<tr><td><INPUT id=KsToRaid type=text size=2 maxlength=2></td><td>'+culang.mainRaid+'</td></tr>\
				<tr><td><INPUT id=KsToApothecary type=text size=2 maxlength=2></td><td>'+culang.tabLabelApothecary+'</td></tr>\
				<tr><td><INPUT id=KsToScoutAlliance type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoScout+'</td></tr>\
				<tr><td><INPUT id=KsToWild type=text size=2 maxlength=2></td><td>'+culang.tabLabelWild+'</td></tr>\
				<tr><td><INPUT id=KsToKnights type=text size=2 maxlength=2></td><td>'+culang.tabLabelKnights+'</td></tr>\
				<tr><td><INPUT id=KsToOptions type=text size=2 maxlength=2></td><td>'+culang.tabLabelOptions+'</td></tr>\
				<tr><td><INPUT id=KsToUserTab type=text size=2 maxlength=2></td><td>'+Options.NewTabName+'</td></tr>\
				<tr><td><INPUT id=KsToKoCScripts type=text size=2 maxlength=2></td><td>KoC Scripts</td></tr>\
				</table>';
				html += '</div></div>';
			}

			/* chatTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'chatTabOptions\');">'+culang.optionsHeadChat+'</a></div>';
				html += '<DIV id="chatTabOptions" style="display:'+Options["chatTabOptions"]+';">';
				html += '<TABLE class=pdxTab>\
				<TR><TD><input  type=checkbox id=pbChatREnable /></td><TD width="696">'+culang.optionsChatRight+'</td></tr>\
				<TR><TD><INPUT id=PubReq type=checkbox '+ (GlobalOptions.autoPublishGamePopups?'CHECKED ':'') +'/></td><TD title="'+culang.optionsAutoPublishOnFacebookNote2+'">'+culang.optionsAutoPublishOnFacebook+' '+ htmlSelector({0:'-- '+culang.mainSelect+' --', 80:''+culang.optionsAutoPublishOnFacebookEveryone+'', 50:''+culang.optionsAutoPublishOnFacebookFriendsOfFriends+'', 40:''+culang.optionsAutoPublishOnFacebookFriendsOnly+'', 10:''+culang.optionsAutoPublishOnFacebookOnlyMe+''},GlobalOptions.autoPublishPrivacySetting,'id=selectprivacymode') +' <sup>(<span class="boldRed">'+culang.optionsAutoPublishOnFacebookNote+'</span>)</sup></td></tr>\
				<TR><TD><INPUT id=ptEnableFoodWarnTchat type=checkbox /></td><TD>'+culang.optionsChatLowFood+' - '+culang.mainIntervall+': <INPUT type=text id=optFoodChatHours value="'+ Options.foodChatWarnHours +'" size=2></td></tr>\
				<TR><TD><INPUT id=HelReq type=checkbox /></td><TD>'+culang.optionsChatHelpReq+'</td></tr>\
				<TR><TD><INPUT id=DelReq type=checkbox /></td><TD>'+culang.optionsChatDelReq+'</td></tr>\
				<TR><TD><INPUT id=DelRules type=checkbox /></td><TD>'+culang.optionsChatDelRules+'</td></tr>\
				<TR><TD><INPUT id=togChatStuff type=checkbox /></td><TD>'+culang.optionsChatExtras+'</td></tr>\
				<TR><TD><INPUT id=KsSmiley type=checkbox /></td><TD>'+culang.mainSmileys+' <INPUT id=EmoHelp type=submit value="'+culang.buttonHelp+'"></td></tr>\
				<TR><TD><INPUT id=togShowMultiUpdateNote type=checkbox '+ (Options.showMultiUpdateNote?'CHECKED ':'') +'/></td><TD colspan=3>'+ htmlSelector({updateFull:culang.optionsPostMulitUpdateShowFull, updateTextImageLike:culang.optionsPostMulitUpdateShowTextImageLike, updateTextImage:culang.optionsPostMulitUpdateShowTextImage, updateText:culang.optionsPostMulitUpdateShowText }, GlobalOptions.updateChatNote,'id=KsUpdateChatNoteSel') +' '+culang.optionsShowMultiUpdateCmd+'</td></tr>\
				<TR><TD><INPUT id=togPostMultiUpdate type=checkbox '+ (Options.postMultiUpdate?'CHECKED ':'') +'/></td><TD colspan=3>'+culang.optionsPostMulitUpdate+'</td></tr>\
				<TR><TD colspan=4>'+culang.optionsPostMulitUpdateSound+' '+culang.mainVolume+' <INPUT id=togMultiUpdateSoundVol size=1 maxlength=1 type=textbox value="'+ Options.multiUpdateSoundVol +'" /> '+culang.optionsPostMulitUpdateSoundAutoPlay+' <INPUT id=togMultiUpdateSoundEnable size=1 maxlength=1 type=textbox value="'+ Options.multiUpdateSoundEnable +'" /> 0 = '+culang.buttonOFF+' 1 = '+culang.buttonON+'</td></tr>\
				</table>';
				html += '</div>';
			}

			
			/* towerTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'towerTabOptions\');" >'+culang.optionsHeadTower+'</a></div>';
				html += '<DIV id="towerTabOptions" style="display:'+Options["towerTabOptions"]+';">';
				html +='<TABLE class=pdxTab>\
				<TR><TD><INPUT id=pcalertEnable type=checkbox '+ (Options.alertConfig.aChat?'CHECKED ':'') +'/></td><TD>'+culang.optionsTowerEnable+' </td></tr>\
				<TR><TD><INPUT id=ksSoundEnable type=checkbox '+ (Options.alertSound.enabled?'CHECKED ':'') +'/></td><TD>'+culang.optionsTowerEnableSounds+'</td></tr>\
				<TR><TD></td><TD><DIV id=boSoundOpts><TABLE cellpadding=0 cellspacing=0>\
				<TR><TD colspan=3>'+culang.optionsSoundsLinks+'</td></tr>\
				<TR><TD align=right>'+culang.optionsSoundURL+': &nbsp; </td><TD><input id=sUrlST type=checkbox '+(Options.alertSound.soundUrlST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.alertSound.soundUrlST==1?'DISABLED':'')+' id=bosoundFile type=text size=60 maxlength=160 value="'+ Options.alertSound.soundUrl +'" \ title="'+culang.optionsSoundURLNote+'"></td><TD><INPUT id=boSoundDefault type=submit value="'+culang.mainDefault+'"></td></tr>\
				<TR><TD align=right>'+culang.mainVolume+': &nbsp; </td><TD><TABLE cellpadding=0 cellspacing=0 class=pdxTab><TR valign=middle><TD><SPAN id=boVolSlider></span></td><TD width=15></td><TD align=right id=boVolOut>0</td></td></table></td><TD align=center><SPAN id=optionsLoadSWF>xx</span></td></tr>\
				<TR><TD align=right><INPUT id=KsSoundRepeat type=checkbox '+ (Options.alertSound.repeat?'CHECKED ':'') +'/></td><TD> '+culang.mainRepeat+' <INPUT id=KsSoundEvery type=text size=2 maxlength=5 value="'+ Options.alertSound.repeatDelay +'"> '+culang.mainMinutes+'</td></tr>\
				<TR><TD></td><TD>'+culang.optionsSoundAlertLenght+' <INPUT id=KsSoundLength type=text size=3 maxlength=5 value="'+ Options.alertSound.playLength +'"> '+culang.mainSeconds+'</td></tr>\
				<TR><TD></td><TD><INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNow> &nbsp; <INPUT id=optionsSoundStop type=submit value="'+culang.buttonStopSound+'"></td></tr></table></div></td></tr><TR><TD></td><TD>';
				html +='<TABLE cellpadding=0 cellspacing=0 class=pdxTab><TR><TD align=right>'+culang.optionsTowerPostSettings+'  : </td><TD>&nbsp;<INPUT id=pcalertSendToAlly type=checkbox '+ (Options.alertConfig.sendtoAlly?'CHECKED ':'') +' /> '+culang.optionsTowerPostSettings2+' <INPUT id=pcalertSendAsWhisper type=checkbox '+ (Options.alertConfig.sendasWhisper?'CHECKED ':'') +' /> '+culang.optionsTowerPostSettings3+' </td></tr>\
				<TR><TD align=right>'+culang.optionsTowerOwnMessage+' &nbsp; </td><TD><INPUT id=pcalertPrefix type=text size=55 maxlength=120 value="'+ Options.alertConfig.aPrefix +'" \></td></tr>\
				<TR><TD align=right>'+culang.optionsTowerAlertIf+' &nbsp; </td><TD><INPUT id=pcalertWild type=checkbox '+ (Options.alertConfig.wilds?'CHECKED ':'') +'/> '+culang.optionsTowerAlertIfWild+'  <INPUT id=pcalertScout type=checkbox '+ (Options.alertConfig.scouting?'CHECKED ':'') +'/> '+culang.optionsTowerAlertIfScout+' </td></tr>\
				<TR><TD align=right>'+culang.optionsTowerMinTroops+' :<br></td><TD><INPUT id=pcalertTroops type=text size=7 value="'+ Options.alertConfig.minTroops +'" \> '+culang.optionsTowerMinTroops2+' <INPUT id=pcalertTroops2 type=text size=7 value="'+ Options.alertConfig.minTroops2 +'" \> '+culang.optionsTowerMinTroops3+' &nbsp; &nbsp; <span id=pcalerterr></span></td></tr>\
				<TR><TD align=right>'+culang.mainDefense+': &nbsp; </td><TD><INPUT id=pbalertDefend type=checkbox '+ (Options.alertConfig.defence?'CHECKED ':'') +' \> &nbsp; &nbsp; </td></tr>\
				<TR><TD align=right>'+culang.optionsTowerFletch+' &nbsp; </td><TD><INPUT id=pcalertFletching type=checkbox '+ (Options.alertConfig.fletching?'CHECKED ':'') +'/></td></tr>\
				<TR><TD align=right>'+culang.optionsTowerThrone+' </td><TD><INPUT id=pcalertTroneRange type=checkbox '+ (Options.alertConfig.TroneRange?'CHECKED ':'') +'/> '+culang.optionsTowerRange+'  <INPUT id=pcalertTroneRangeDebuff type=checkbox '+ (Options.alertConfig.TroneRangeDebuff?'CHECKED ':'') +'/> '+culang.optionsTowerRangeDebuff+' </td></tr>\
				<TR><TD align=right>'+culang.mainKnights+' ('+culang.mainWithoutBosster+'): &nbsp; </td><TD><INPUT id=pcalertMarechal type=checkbox '+ (Options.alertConfig.marechal?'CHECKED ':'') +'/></td></tr>\
				<TR><TD align=right>'+culang.optionsTowerDefBooster+' &nbsp; </td><TD><INPUT id=pcalertdefBoost type=checkbox '+ (Options.alertConfig.defBoost?'CHECKED ':'') +'/></td></tr>\
				<TR><TD align=right>'+culang.mainEmbassy+': &nbsp; </td><TD><INPUT id=pcalertEmbassy type=checkbox '+ (Options.alertConfig.embassy?'CHECKED ':'') +'/></td></tr>\
				<TR><TD align=right>'+culang.mainDefense+': &nbsp; </td><TD><INPUT id=pcalertMytroops type=checkbox '+ (Options.alertConfig.mytroops?'CHECKED ':'') +'/>'+culang.mainTroops+' <INPUT id=pcalertDefense type=checkbox '+ (Options.alertConfig.defense?'CHECKED ':'') +' /> '+culang.mainWall+' </td></tr>\
				<TR><TD align=right>'+culang.optionsTowerFoodLeft+': &nbsp; </td><TD><INPUT id=pcalertFood type=checkbox '+ (Options.alertConfig.food?'CHECKED ':'') +' /></td></tr>\
				<TR><TD align=right>'+culang.optionsTowerHideHQ+':</td><td><INPUT id=pcalertQG type=checkbox '+ (Options.alertConfig.MonQG?'CHECKED ':'') +' /></td></tr>\
				<TR><TD align=right>'+culang.optionsTowerStopOnAttack+':</td><td><INPUT id=Ksalertraid type=checkbox '+ (Options.alertConfig.raid?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackRaid+'  <INPUT id=Ksalertappro type=checkbox '+ (Options.alertConfig.appro?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackSupply+'  <INPUT id=Ksalertautofo type=checkbox '+ (Options.alertConfig.autofo?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackDarkForest+' <INPUT id=Ksalertautots type=checkbox '+ (Options.alertConfig.autots?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackCrest+' </td></tr>\
				<TR><TD align=right>' + culang.mainChangeThroneSet + ':</td><td><INPUT id=Ksalertthrone type=checkbox '+ (Options.alertConfig.changeThrone?'CHECKED':'') +'/> ' + culang.mainToThroneSet + ': <SELECT id=KsalertTSet>';
				for (i=1;i<=Seed.throne.slotNum;i++){html += '<option value="'+i+'">'+i+'</option>';}
				html +='</select> ' + culang.mainWhenAttacked + '</td>\
				<TR><TD align=right>' + culang.mainResetThrone + ':</td><td><INPUT id=KsalertthroneRet type=checkbox '+ (Options.alertConfig.returnThrone?'CHECKED':'') +'/> ' + culang.mainToThroneSet + ': <SELECT id=KsalertTSetRet>';
				for (i=1;i<=Seed.throne.slotNum;i++){html += '<option value="'+i+'">'+i+'</option>';}
				html +='</select> ' + culang.mainIf + ' <input type="text" id=KsalertthroneMin style="text-align:center;" size=3 maxlength=5 value="'+Options.alertConfig.returnThroneMin+'"> ' + culang.mainMinutesNoAttack + '</td></tr>\
						<TR><TD align=right>'+culang.optionsTowerEMail+'<sup><span class="boldRed">'+culang.optionsTowerEMailNote+'</span></td><TD><INPUT id=Ksalertemail type=checkbox '+ (Options.alertConfig.email?'CHECKED ':'') +'/></td></tr>\
						</table></table><DIV id=KsFacebookConnect></div>';
					
				html += '</div>';
			}
			
			/* soundsTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'soundsTabOptions\');" title="'+culang.optionsHeadSoundsNote+'">'+culang.optionsHeadSounds+'</a></div>';
				html += '<DIV id="soundsTabOptions" style="display:'+Options["soundsTabOptions"]+';">';
				html += '<TABLE class=pdxTab>\
				<TR><TD colspan=4>'+culang.optionsSoundsLinks+'</td></tr>\
				<TR><TD><INPUT id=togWhisperOn type=checkbox /></td><TD>'+culang.optionsChatWhisperSound+'</td><TD><input id=stURL1 type=checkbox '+(Options.URLson1ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLson1ST==1?'DISABLED':'')+' id=togURL1 size=50 type=textbox value="'+ Options.URLson1 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLson1Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson1Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL1"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNow1></td></tr>\
				<TR><TD><INPUT id=togEclaireurOn type=checkbox /></td><TD>'+culang.optionsChatScoutSound+'</td><TD><input id=stURL4 type=checkbox '+(Options.URLson4ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLson4ST==1?'DISABLED':'')+' id=togURL4 size=50 type=textbox value="'+ Options.URLson4 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLson4Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson4Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL4"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNow4></td></tr>\
				<TR><TD><INPUT id=togAttaqueOn type=checkbox /></td><TD>'+culang.optionsChatAttackSound+'</td><TD><input id=stURL2 type=checkbox '+(Options.URLson2ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLson2ST==1?'DISABLED':'')+' id=togURL2 size=50 type=textbox value="'+ Options.URLson2 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLson2Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson2Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL2"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNow2></td></tr>\
				<TR><TD><INPUT id=togWildSoundOn type=checkbox /></td><TD>'+culang.optionsChatWildSound+'</td><TD><input id=stURL5 type=checkbox '+(Options.URLson5ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLson5ST==1?'DISABLED':'')+' id=togURL5 size=50 type=textbox value="'+ Options.URLson5 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLson5Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson5Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL5"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNow5></td></tr>\
				<TR><TD><INPUT id=togFoodSoundOn type=checkbox /></td><TD>'+culang.optionsChatFoodSound+'</td><TD><input id=stURL6 type=checkbox '+(Options.URLson6ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLson6ST==1?'DISABLED':'')+' id=togURL6 size=50 type=textbox value="'+ Options.URLson6 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLson6Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson6Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL6"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNow6></td></tr>\
				<TR><TD><INPUT id=togKsFunSoundAttack type=checkbox /></td><TD>'+culang.optionsSoundFunChatCommands+' '+culang.optionsSoundGetFSAttack+' - '+culang.optionsSoundFunSoundURL+'</td><TD><input id=stURLF1 type=checkbox '+(Options.URLsonF1ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLsonF1ST==1?'DISABLED':'')+' id=togURLF1 size=50 type=textbox value="'+ Options.soundURLF1 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLF1vol size=3 type=textbox value="'+ Options.URLsonF1vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="PDXDefURLF1"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNowF1></td></tr>\
				<TR><TD><INPUT id=togKsFunSoundHorn type=checkbox /></td><TD>'+culang.optionsSoundFunChatCommands+' '+culang.optionsSoundGetFSHorn+' - '+culang.optionsSoundFunSoundURL+'</td><TD><input id=stURLF2 type=checkbox '+(Options.URLsonF2ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLsonF2ST==1?'DISABLED':'')+' id=togURLF2 size=50 type=textbox value="'+ Options.soundURLF2 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLF2vol size=3 type=textbox value="'+ Options.URLsonF2vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="PDXDefURLF2"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNowF2></td></tr>\
				<TR><TD><INPUT id=togKsFunSoundGun type=checkbox /></td><TD>'+culang.optionsSoundFunChatCommands+''+culang.optionsSoundGetFSGun+' - '+culang.optionsSoundFunSoundURL+'</td><TD><input id=stURLF3 type=checkbox '+(Options.URLsonF3ST==1?'CHECKED':'')+'>&nbsp;<INPUT '+(Options.URLsonF3ST==1?'DISABLED':'')+' id=togURLF3 size=50 type=textbox value="'+ Options.soundURLF3 +'" /></td><TD>'+culang.optionsChatSoundVolume+' <INPUT id=togURLF3vol size=3 type=textbox value="'+ Options.URLsonF3vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="PDXDefURLF3"> <INPUT type=submit value="'+culang.buttonPlaySound+'" id=KsPlayNowF3></td></tr></table>';
				html += '</div>';
			}
			
			/* colorsTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'colorsTabOptions\');">'+culang.optionsHeadColors+'</a> (<a target=_blank href="http://kocscripts.com/koc/colors.html" title="'+culang.optionsChatSelectColorNote+'">'+culang.optionsChatSelectColor+'</a>)</div>';
				html += '<DIV id="colorsTabOptions" style="display:'+Options["colorsTabOptions"]+';">';	
				html += '<TABLE class=pdxTab>\
				<TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatScoutAlert style="background-color:'+Colors.ChatEcl+'" type=text size=7 maxlength=7 value="'+Colors.ChatEcl+'"> '+culang.optionsChatScoutBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatScoutAlertFont style="background-color:'+Colors.ChatEclFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatEclFont+'"></td></tr>\
				<TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatAtt style="background-color:'+Colors.ChatAtt+'" type=text size=7 maxlength=7 value="'+Colors.ChatAtt+'"> '+culang.optionsChatAttackBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatAttFont style="background-color:'+Colors.ChatAttFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatAttFont+'"></td></tr>\
				<TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatWildAtt style="background-color:'+Colors.ChatWildAtt+'" type=text size=7 maxlength=7 value="'+Colors.ChatWildAtt+'"> '+culang.optionsChatWildAttackBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatWildAttFont style="background-color:'+Colors.ChatWildAttFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatWildAttFont+'"></td></tr>\
				<TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatLowFood style="background-color:'+Colors.ChatLowFood+'" type=text size=7 maxlength=7 value="'+Colors.ChatLowFood+'"> '+culang.optionsChatLowFoodBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatLowFoodFont style="background-color:'+Colors.ChatLowFoodFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatLowFoodFont+'"></td></tr>\
				<TR><TD>&nbsp;</td><TD><INPUT id=togChatGlo style="background-color:'+Colors.ChatGlo+'" type=text size=7 maxlength=7 value="'+Colors.ChatGlo+'"> '+culang.optionsChatGlobalBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatGloFont style="background-color:'+Colors.ChatGloFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatGloFont+'"></td></tr>\
				<TR><TD>&nbsp;</td><TD><INPUT id=togChatAlliance style="background-color:'+Colors.ChatAlliance+'" type=text size=7 maxlength=7 value="'+Colors.ChatAlliance+'"> '+culang.optionsChatAllianceBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatAllianceFont style="background-color:'+Colors.ChatAllianceFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatAllianceFont+'"></td></tr>\
				<TR><TD colspan=2><INPUT id=KsChatLeader type=checkbox /> '+culang.optionsChatLeaderBG+'</td></tr>\
				<TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatC style="background-color:'+Colors.ChatChancy+'" type=text size=7 maxlength=7 value="'+Colors.ChatChancy+'"> '+culang.mainChancellor+'</td></tr>\
				<TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatVC style="background-color:'+Colors.ChatVC+'" type=text size=7 maxlength=7 value="'+Colors.ChatVC+'"> '+culang.mainViceChancellor+' </td></tr>\
				<TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatLeaders style="background-color:'+Colors.ChatLeaders+'" type=text size=7 maxlength=7 value="'+Colors.ChatLeaders+'"> '+culang.mainOfficer+' </td></tr>\
				</table>\
				<TABLE class=pdxTab>\
				<TR><td>'+culang.optionsColorsMainTitle+'</td><TD><INPUT id=togMainTitle style="background-color:'+Colors.MainTitle+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle+'"> '+culang.optionsChatFontcolor+' - <INPUT id=togMainTitleHover style="background-color:'+Colors.MainTitleHover+'" type=text size=7 maxlength=7 value="'+Colors.MainTitleHover+'"> '+culang.optionsColorsHover+' <INPUT id=togMainTitleBackground style="background-color:'+Colors.MainTitleBackground+'" type=text size=7 maxlength=7 value="'+Colors.MainTitleBackground+'"> '+culang.optionsColorsBackground+'</td></tr>\
				<TR><td>'+culang.optionsColorsSubMainTitle+'</td><TD><INPUT id=togMainTitle2 style="background-color:'+Colors.MainTitle2+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle2+'"> '+culang.optionsChatFontcolor+' - <INPUT id=togMainTitle2Hover style="background-color:'+Colors.MainTitle2Hover+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle2Hover+'"> '+culang.optionsColorsHover+' <INPUT id=togMainTitle2Background style="background-color:'+Colors.MainTitle2Background+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle2Background+'"> '+culang.optionsColorsBackground+'</td></tr>\
				</table>';
				html += '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'colorsChatTabOptions\').style.display=(document.getElementById(\'colorsChatTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsColorsHead+'</a></div>';
				html += '<DIV id="colorsChatTabOptions" style="display:none;">';
				html += '<TABLE class=pdxTab>\<TR><TD><b><u>'+culang.mainPlayer+'</u></b> </td><TD><b><u>'+culang.optionsColorsColor+'</u></b> </td><TD width="153" ><b><u>'+culang.mainName+'</u></b></td><TD><b><u>'+culang.mainPlayer+'</u></b> </td><TD><b><u>'+culang.optionsColorsColor+'</u></b> </td><TD width="144" ><u><b>'+culang.mainName+'</b></u></td></tr>		<TR><TD width="200" ><INPUT  type=checkbox id=ptEnableUserName1 />  '+culang.mainPlayer+' #1 </td><TD  width="44" ><INPUT  style="background:'+Colors.userBG1+'" type=text id=toguserBG1 value="'+Colors.userBG1+'" size=7 maxlength=7></td><TD><input type=text id=togcolorUserName1 value="'+ Options.userName1 +'"></td><TD width="200" ><INPUT  type=checkbox id=ptEnableUserName16 /> '+culang.mainPlayer+' #16 </td><TD  width="44" ><INPUT  style="background:'+Colors.userBG16+'" type=text id=toguserBG16 value="'+Colors.userBG16+'" size=7 maxlength=7></td><TD><input type=text id=togcolorUserName16 value="'+ Options.userName16 +'"></td></tr>		<TR><TD ><INPUT  type=checkbox id=ptEnableUserName2 /> '+culang.mainPlayer+' #2 </td><TD  ><INPUT style="background:'+Colors.userBG2+'" type=text id=toguserBG2 value="'+Colors.userBG2+'" size=7 maxlength=7></td><TD ><INPUT  type=text id=togcolorUserName2 value="'+ Options.userName2 +'"></td><TD ><INPUT  type=checkbox id=ptEnableUserName17 />'+culang.mainPlayer+' #17 </td><TD ><INPUT  style="background:'+Colors.userBG17+'"  type=text id=toguserBG17 value="'+Colors.userBG17+'" size=7 maxlength=7></td><TD ><INPUT  type=text id=togcolorUserName17 value="'+ Options.userName17 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName3 /> '+culang.mainPlayer+' #3</td><TD ><INPUT style="background:'+Colors.userBG3+'" type=text id=toguserBG3 value="'+Colors.userBG3+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName3 value="'+ Options.userName3 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName18 /> '+culang.mainPlayer+' #18 </td><TD ><INPUT style="background:'+Colors.userBG18+'" type=text id=toguserBG18 value="'+Colors.userBG18+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName18 value="'+ Options.userName18 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName4 /> '+culang.mainPlayer+' #4 </td><TD  ><INPUT style="background:'+Colors.userBG4+'" type=text id=toguserBG4 value="'+Colors.userBG4+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName4 value="'+ Options.userName4 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName19 />'+culang.mainPlayer+' #19 </td><TD><INPUT  style="background:'+Colors.userBG19+'"  type=text id=toguserBG19 value="'+Colors.userBG19+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName19 value="'+ Options.userName19+'"></td></tr>		<TR ><TD><INPUT type=checkbox id=ptEnableUserName5 /> '+culang.mainPlayer+' #5 </td><TD ><INPUT style="background:'+Colors.userBG5+'" type=text id=toguserBG5 value="'+Colors.userBG5+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName5 value="'+ Options.userName5 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName20 />'+culang.mainPlayer+' #20 </td><TD ><INPUT style="background:'+Colors.userBG20+'" type=text id=toguserBG20 value="'+Colors.userBG20+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName20 value="'+ Options.userName20 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName6 /> '+culang.mainPlayer+' #6 </td><TD ><INPUT style="background:'+Colors.userBG6+'" type=text id=toguserBG6 value="'+Colors.userBG6+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName6 value="'+ Options.userName6 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName21 /> '+culang.mainPlayer+' #21 </td><TD ><INPUT style="background:'+Colors.userBG21+'" type=text id=toguserBG21 value="'+Colors.userBG21+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName21 value="'+ Options.userName21 +'"></td></tr>		<TR ><TD><INPUT  type=checkbox id=ptEnableUserName7 /> '+culang.mainPlayer+' #7 </td><TD ><INPUT style="background:'+Colors.userBG7+'" type=text id=toguserBG7 value="'+Colors.userBG7+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName7 value="'+ Options.userName7 +'"></td><TD><INPUT  type=checkbox id=ptEnableUserName22 /> '+culang.mainPlayer+' #22</td><TD ><INPUT style="background:'+Colors.userBG22+'" type=text id=toguserBG22 value="'+Colors.userBG22+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName22 value="'+ Options.userName22 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName8 /> '+culang.mainPlayer+' #8 </td><TD ><INPUT style="background:'+Colors.userBG8+'" type=text id=toguserBG8 value="'+Colors.userBG8+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName8 value="'+ Options.userName8 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName23 />     '+culang.mainPlayer+' #23 </td><TD ><INPUT style="background:'+Colors.userBG23+'" type=text id=toguserBG23 value="'+Colors.userBG23+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName23 value="'+ Options.userName23 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName9 /> '+culang.mainPlayer+' #9 </td><TD ><INPUT style="background:'+Colors.userBG9+'" type=text id=toguserBG9 value="'+Colors.userBG9+'" size=7 maxlength=7></td><TD ><input type=text id=togcolorUserName9 value="'+ Options.userName9 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName24 />     '+culang.mainPlayer+' #24 </td><TD ><INPUT style="background:'+Colors.userBG24+'" type=text id=toguserBG24 value="'+Colors.userBG24+'" size=7 maxlength=7></td><TD ><input type=text id=togcolorUserName24 value="'+ Options.userName24 +'"></td></tr>		<TR ><TD><INPUT type=checkbox id=ptEnableUserName10 /> '+culang.mainPlayer+' #10 </td><TD ><INPUT style="background:'+Colors.userBG10+'" type=text id=toguserBG10 value="'+Colors.userBG10+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName10 value="'+ Options.userName10 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName25 /> '+culang.mainPlayer+' #25 </td><TD ><INPUT style="background:'+Colors.userBG25+'" type=text id=toguserBG25 value="'+Colors.userBG25+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName25 value="'+ Options.userName25 +'"></td></tr>		<TR ><TD width="180" ><INPUT  type=checkbox id=ptEnableUserName11 /> '+culang.mainPlayer+' #11 </td><TD  width="44" ><INPUT style="background:'+Colors.userBG11+'" type=text id=toguserBG11 value="'+Colors.userBG11+'" size=7 maxlength=7></td><TD><input type=text id=togcolorUserName11 value="'+ Options.userName11 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName26 /> '+culang.mainPlayer+' #26 </td><TD ><INPUT style="background:'+Colors.userBG26+'" type=text id=toguserBG26 value="'+Colors.userBG26+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName26 value="'+ Options.userName26 +'"></td></tr>		<TR ><TD ><INPUT  type=checkbox id=ptEnableUserName12 />'+culang.mainPlayer+' #12 </td><TD  ><INPUT style="background:'+Colors.userBG12+'" type=text id=toguserBG12 value="'+Colors.userBG12+'" size=7 maxlength=7></td><TD ><INPUT  type=text id=togcolorUserName12 value="'+ Options.userName12 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName27 /> '+culang.mainPlayer+' #27 </td><TD ><INPUT style="background:'+Colors.userBG27+'" type=text id=toguserBG27 value="'+Colors.userBG27+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName27 value="'+ Options.userName27 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName13 />'+culang.mainPlayer+' #13 </td><TD ><INPUT style="background:'+Colors.userBG13+'" type=text id=toguserBG13 value="'+Colors.userBG13+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName13 value="'+ Options.userName13 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName28 /> '+culang.mainPlayer+' #28 </td><TD ><INPUT  style="background:'+Colors.userBG28+'" type=text id=toguserBG28 value="'+Colors.userBG28+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName28 value="'+ Options.userName28 +'"></td></tr>		<TR ><TD ><INPUT type=checkbox id=ptEnableUserName14 /> '+culang.mainPlayer+' #14 </td><TD ><INPUT style="background:'+Colors.userBG14+'" type=text id=toguserBG14 value="'+Colors.userBG14+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName14 value="'+ Options.userName14 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName29 /> '+culang.mainPlayer+' #29 </td><TD><INPUT  style="background:'+Colors.userBG29+'" type=text id=toguserBG29 value="'+Colors.userBG29+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName29 value="'+ Options.userName29 +'"></td></tr>		<TR ><TD><INPUT type=checkbox id=ptEnableUserName15 />     '+culang.mainPlayer+' #15  </td><TD ><INPUT style="background:'+Colors.userBG15+'" type=text id=toguserBG15 value="'+Colors.userBG15+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName15 value="'+ Options.userName15 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName30 /> '+culang.mainPlayer+' #30 </td><TD ><INPUT style="background:'+Colors.userBG30+'" type=text id=toguserBG30 value="'+Colors.userBG30+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName30 value="'+ Options.userName30 +'"></td></tr>\
				</table>';
				html += '</div></div>';	
				}
				
			/* styleTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'styleTabOptions\').style.display=(document.getElementById(\'styleTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadStyle+'</a></div>';
				html += '<DIV id="styleTabOptions" style="display:none;">';
				html += '<TABLE class=pdxTab>\
				<TD width=2%></td><TD width=66%>'+culang.optionsPopupBorderRadius+' <INPUT type=text id=KspopupBorderRadius size=19 maxlength=19 value="'+ Options.popupBorderRadius +'" /> <sup>(<span class=boldRed>'+culang.optionsPopupBorderRadiusNote+'</span>)</sup></td></tr>\
				<TD width=2%><INPUT id=ptAllowTransparent type=checkbox /></td><TD width=66%>10% '+culang.optionsPopupTransparent+' </td></tr>\
				<TD colspan="2">'+culang.optionsPopupHeight+': <INPUT  type=text id="optHauteurBoite" value="'+ Options.HauteurBoite +'" size=4>'+culang.optionsPopupHeight2+'</td></tr>\
				<TR><TD></td><TD colspan=3><INPUT id=togCustomWideScreenSize type=text size=4 value="'+GlobalOptions.customWideScreenSize+'"/>'+culang.optionsCustomWideScreen+'</td>\
				<TR><TD><INPUT id=boWideOpt type=checkbox '+ (GlobalOptions.pbWideScreen?'CHECKED ':'') +'/></td><TD colspan="3">'+culang.mainWideScreen+': '+ htmlSelector({normal:culang.mainNormal, wide:culang.mainWideScreen, ultra:culang.mainUltra,custom:culang.mainCustom},GlobalOptions.pbWideScreenStyle,'id=KsselectScreenMode') +'</td>\
				<TR><TD width=5%><INPUT id=pbWMapEnable type=checkbox /></td><TD width=27%>'+culang.optionsWideMap+'</td></tr>\
				<TR><TD><INPUT id=MapExtra type=checkbox /></td><TD>'+culang.optionsMapExtras+'</td></tr>\
				<TR><TD><INPUT id=togKsBadge type=checkbox /></td><TD>KoC Power All - EMH ELITE Badge</td></tr>\
				<TR><TD><INPUT id=KsLangFlag type=checkbox /></td><TD>'+culang.optionsLangFlagChat+' <img height=16 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="'+culang.KsRunningLanguage+'"></td></tr>\
				<TR><TD><INPUT id=KsHyperlinks type=checkbox /></td><TD>'+culang.optionsHyperlinksChat+'</td></tr>\
				</table>';
				html += '</div>';
			}

			/* avatarTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'avatarTabOptions\');">'+culang.optionsHeadAvatars+'</a></div>';
				html += '<DIV id="avatarTabOptions" style="display:'+Options["avatarTabOptions"]+';">';
				html += '<TABLE class=pdxTab2>\
				<TR><TD><INPUT id=user_icon type=checkbox /></td> <TD>'+culang.optionsChatOwnAvatar+' <INPUT id=togURL3 size=30 type=textbox value="'+Options.URLicon+'" /><input type=button value="'+culang.mainDefault+'" id="KsDefURL3"/> ('+culang.optionsChatOwnAvatar2+')</td></tr></table>\
				<TR><TD><INPUT id=user_iconFlag type=checkbox /></td> <TD>'+culang.optionsChatLangFlag+'</td></tr></table>\
				<div class=pdxStat2>'+culang.optionsAvatarHeadMore+'</div>'+culang.optionsAvatarNote+'<HR><font color=#5555CC><b>'+culang.playerSearchPlayerUserID+'</b> <span title="'+culang.optionsUserIDNote+'">'+parseInt([Seed.tutorial.userId])+'</span><BR>'+culang.optionsAvatarForm+'';
				html += '</div>';
			}
			// <img src="'+Options.URLicon+'">
			
			/* reportTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'reportTabOptions\');">'+culang.optionsHeadReports+'</a></div>';
				html += '<DIV id="reportTabOptions" style="display:'+Options["reportTabOptions"]+';">';
				html += '<TABLE class=pdxTab>\
				<TR><TD><INPUT id=togRptGift type=checkbox /></td><TD>'+culang.optionsReportsDelInboxGifts+'</td></tr>\
				<TR><TD><INPUT id=togAllRpts type=checkbox /></td><TD>'+culang.optionsReportsExtras+'</td></tr>\
				<TR><TD><INPUT id=togAllMembers type=checkbox /></td><TD>'+culang.optionsReportsViewMember+'</td></tr>\
				<TR><TD><INPUT id=togAtkDelete type=checkbox DISABLED/></td><TD>'+culang.optionsReportsDeleteButton+'</td></tr>\
				<TR><TD></td><td>'+culang.optionsReportsAutoDelete+' <input type=button id=bodeletenow value="'+culang.mainDeleteNow+'">'+
				' (<INPUT id=DeleteReportDebug type=checkbox '+(DeleteReports.trace?'CHECKED':'')+'/>Debug)'+'</tr>\
				<TR><td></td><TD colspan=1><INPUT id=delete4toggle type=checkbox />'+culang.optionsReportsAutoDeleteScout+' <br><INPUT id=deletetoggle type=checkbox /> '+culang.optionsReportsAutoDeleteBarbTrans+'&nbsp;<br><INPUT id=deletes0toggle type=checkbox /> '+culang.optionsReportsAutoDeleteTransport+'<br><INPUT id=deletes1toggle type=checkbox />'+culang.mainWildernes+'<br><INPUT id=deletes2toggle type=checkbox />'+uW.g_js_strings.commonstr.darkForest+'&nbsp;<br><INPUT id=deletes3toggle type=checkbox /> '+culang.mainReinforce+'<br><INPUT id=deletes5toggle type=checkbox /> '+culang.mainAttack+'<br><INPUT id=deletes6toggle type=checkbox /> '+culang.optionsReportsAutoDeleteCrestCity+'</td></tr>\
				<TR><TD></td><td> '+culang.mainIntervall+': <input type=text size=3 id=Ksdeletetimer value="' + Options.DeleteTimerMinute + '"> '+culang.mainMinutes+' </td></tr></table>';
				html += '</div>';
			}

			/* bugFixesTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'bugFixesTabOptions\');" >'+culang.optionsHeadBugFixes+'</a></div>';
				html += '<DIV id="bugFixesTabOptions" style="display:'+Options["bugFixesTabOptions"]+';">';
				html += '<TABLE class=pdxTab>\
				<TR><TD><INPUT id=togKnightSelect type=checkbox /></td><TD>'+culang.optionsBugDisableKnightSel+'  ('+culang.optionsBugDisableKnightSel2+')</td></tr>\
				<TR><TD><INPUT id=togCoordBox type=checkbox /></td><TD>'+culang.optionsBugCoordBox+'</td></tr>\
				<TR><TD><INPUT id=togMightKoCBugFix type=checkbox /></td><TD>'+culang.optionsBugMightFix+'</td></tr>\
				<TR><TD><INPUT id=togResKoCBugFix type=checkbox /></td><TD>'+culang.optionsBugResFix+'</td></tr>\
				<TR style="display:none;"><TD><INPUT id=togMapDistFix type=checkbox /></td><TD>'+culang.optionsBugMapDistance+'</td></tr></table>';
				html += '</div>';
			}

			/* resetTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'resetTabOptions\');" title="'+culang.optionsHeadResetNote+'">'+culang.optionsHeadReset+'</a></div>';
				html += '<DIV id="resetTabOptions" style="display:'+Options["resetTabOptions"]+';">';
				html +='<TABLE class=pdxTab>\
				<TR><TD><b><u>'+culang.mainGenerally+'</u></b></td><TD><b><u>'+culang.mainAutoFunc+'</u></b></td></tr>\
				<TR><TD>'+strButton20(''+culang.buttonResetOptions+'', 'id=KsResetALL')+'</td><TD>	'+strButton20(''+culang.buttonResetDF+'', 'id=KsResetDF')+'</td></tr>\
				<TR><TD>'+ strButton20(culang.buttonResetTabOrderPower, 'id=togResetStyleOpt') +'</td><TD>	</td></tr>\
				<TR><TD>'+strButton20(''+culang.buttonResetColors+'', 'id=ResetALL')+'</td><TD>	</td></tr>\
	</table>';
				html += '</div>';
			}

			/* exportTabOptions */
			if(true){
				html += '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'exportTabOptions\');" title="'+culang.optionsHeadImpExportNote+'">'+culang.optionsHeadImpExport+'</a></div>';
				html += '<DIV id="exportTabOptions" style="display:'+Options["exportTabOptions"]+';">';
				html += '<TABLE align="center"><TD><input type="submit" value="'+culang.optionsImport+'" id="pbImport_submit"></td><TD><input type="submit" value="'+culang.optionsExport+'" id="pbexport_submit"></td></table>';
				html += '<BR><textarea type="text" id="pbImportData" rows=20 cols=65></textarea>';
				html += '</div>';
			}
       		
			html +="</div>";

			t.cont.innerHTML = html;
			
			t.togOpt ('togRptGift', 'enhancedinbox', DispReport.setEnable, DispReport.isDispReportAvailable);

			// if (Options.pdxLangFlag) { document.getElementById('pdxLangFlag').innerHTML = '<img height=24 width=24 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="Du Benutz zur Zeit die Deutsche version vergiss nicht das Spiel selbst auch auf die gleiche Sprache einszustellen!">'; }
		ById('pbFoodWarning').addEventListener('keyup',function(){DashboardOptions.foodLevel = this.value;saveDashboardOptions();},false);
        ById('pbWoodWarning').addEventListener('keyup',function(){DashboardOptions.woodLevel = this.value;saveDashboardOptions();},false);
        ById('pbStoneWarning').addEventListener('keyup',function(){DashboardOptions.stoneLevel = this.value;saveDashboardOptions();},false);
        ById('pbOreWarning').addEventListener('keyup',function(){DashboardOptions.oreLevel = this.value;saveDashboardOptions();},false);
        ById('pbAStoneWarning').addEventListener('keyup',function(){DashboardOptions.astoneLevel = this.value;saveDashboardOptions();},false);
		ById('togKsShowStatus').addEventListener('change',function(){DashboardOptions.showMultiNote = ById('togKsShowStatus').checked;saveDashboardOptions();},false);
        ById('pbShowThrone').addEventListener('change',function(){DashboardOptions.showThrone = ById('pbShowThrone').checked;saveDashboardOptions();},false);
        ById('pbShowRP').addEventListener('change',function(){DashboardOptions.showRP = ById('pbShowRP').checked;saveDashboardOptions();},false);
        ById('pbShowStatus').addEventListener('change',function(){DashboardOptions.showStatus = ById('pbShowStatus').checked;saveDashboardOptions();},false);
        ById('pbShowTroops').addEventListener('change',function(){DashboardOptions.showTroops = ById('pbShowTroops').checked;saveDashboardOptions();},false);      
        ById('pbShowTower').addEventListener('change',function(){DashboardOptions.showTower = ById('pbShowTower').checked;saveDashboardOptions();},false);      
        ById('pbShowWarnings').addEventListener('change',function(){DashboardOptions.showWarnings = ById('pbShowWarnings').checked;saveDashboardOptions();},false);
        ById('pbShowLog').addEventListener('change',function(){DashboardOptions.showLog = ById('pbShowLog').checked;saveDashboardOptions();},false);
        ById('pbShowMarches').addEventListener('change',function(){DashboardOptions.showMarches = ById('pbShowMarches').checked;saveDashboardOptions();},false);
		
			ById('pbexport_submit').addEventListener('click', t.doExport, false);
			ById('pbImport_submit').addEventListener('click', t.doImport, false); 

			ById('EmoHelp').addEventListener('click', function(){t.EmoHelp();} , false);
			// ById('boaideoptions').addEventListener('click', function(){
			// window.open(homePage+" ");
			// } , false);

			ById('DeleteReportDebug').addEventListener('click', function(){ 
				DeleteReports.trace=ById('DeleteReportDebug').checked;
			}, false);
			
			ById('bodeletenow').addEventListener('click', function(){ DeleteReports.startdeletereports(); }, false);
			t.togOpt ('togAtkDelete', 'reportDeleteButton');
			t.togOpt ('KsNewTab', 'NewTab');
			t.togOpt ('KsIdHomeTab', 'KsHomeTab');

			ById('KsNewTabURL').addEventListener ('change', function () {
				Options.NewTabURL = ById('KsNewTabURL').value;
				saveOptions();
			}, false);
			ById('KsNewTabName').addEventListener ('change', function () {
				Options.NewTabName = ById('KsNewTabName').value;
				saveOptions();
			}, false);

			ById('togChatLeaders').addEventListener('change', function(){
				Colors.ChatLeaders = ById('togChatLeaders').value;
				ById('togChatLeaders').style.backgroundColor=ById('togChatLeaders').value;
			}, false);
			ById('togMainTitle').addEventListener('change', function(){
				Colors.MainTitle = ById('togMainTitle').value;
				ById('togMainTitle').style.backgroundColor=ById('togMainTitle').value;
			}, false);
			ById('togMainTitleHover').addEventListener('change', function(){
				Colors.MainTitleHover = ById('togMainTitleHover').value;
				ById('togMainTitleHover').style.backgroundColor=ById('togMainTitleHover').value;
			}, false);
			ById('togMainTitleBackground').addEventListener('change', function(){
				Colors.MainTitleBackground = ById('togMainTitleBackground').value;
				ById('togMainTitleBackground').style.backgroundColor=ById('togMainTitleBackground').value;
			}, false);
			ById('togMainTitle2').addEventListener('change', function(){
				Colors.MainTitle2 = ById('togMainTitle2').value;
				ById('togMainTitle2').style.backgroundColor=ById('togMainTitle2').value;
			}, false);
			ById('togMainTitle2Hover').addEventListener('change', function(){
				Colors.MainTitle2Hover = ById('togMainTitle2Hover').value;
				ById('togMainTitle2Hover').style.backgroundColor=ById('togMainTitle2Hover').value;
			}, false);
			ById('togMainTitle2Background').addEventListener('change', function(){
				Colors.MainTitle2Background = ById('togMainTitle2Background').value;
				ById('togMainTitle2Background').style.backgroundColor=ById('togMainTitle2Background').value;
			}, false);
			ById('togChatVC').addEventListener('change', function(){
				Colors.ChatVC = ById('togChatVC').value;
				ById('togChatVC').style.backgroundColor=ById('togChatVC').value;
			}, false);
			ById('togChatC').addEventListener('change', function(){
				Colors.ChatChancy = ById('togChatC').value;
				ById('togChatC').style.backgroundColor=ById('togChatC').value;
			}, false);
			ById('togChatAtt').addEventListener('change', function(){
				Colors.ChatAtt = ById('togChatAtt').value;
				ById('togChatAtt').style.backgroundColor=ById('togChatAtt').value;
			}, false);
			ById('togChatAttFont').addEventListener('change', function(){
				Colors.ChatAttFont = ById('togChatAttFont').value;
				ById('togChatAttFont').style.backgroundColor=ById('togChatAttFont').value;
			}, false);
			ById('togChatWildAtt').addEventListener('change', function(){
				Colors.ChatWildAtt = ById('togChatWildAtt').value;
				ById('togChatWildAtt').style.backgroundColor=ById('togChatWildAtt').value;
			}, false);
			ById('togChatWildAttFont').addEventListener('change', function(){
				Colors.ChatWildAttFont = ById('togChatWildAttFont').value;
				ById('togChatWildAttFont').style.backgroundColor=ById('togChatWildAttFont').value;
			}, false);
			ById('togChatLowFood').addEventListener('change', function(){
				Colors.ChatLowFood = ById('togChatLowFood').value;
				ById('togChatLowFood').style.backgroundColor=ById('togChatLowFood').value;
			}, false);
			ById('togChatLowFoodFont').addEventListener('change', function(){
				Colors.ChatLowFoodFont = ById('togChatLowFoodFont').value;
				ById('togChatLowFoodFont').style.backgroundColor=ById('togChatLowFoodFont').value;
			}, false);
			ById('togChatScoutAlert').addEventListener('change', function(){
				Colors.ChatEcl = ById('togChatScoutAlert').value;
				ById('togChatScoutAlert').style.backgroundColor=ById('togChatScoutAlert').value;
			}, false);
			ById('togChatScoutAlertFont').addEventListener('change', function(){
				Colors.ChatEclFont = ById('togChatScoutAlertFont').value;
				ById('togChatScoutAlertFont').style.backgroundColor=ById('togChatScoutAlertFont').value;
			}, false);
			ById('togChatGlo').addEventListener('change', function(){
				Colors.ChatGlo = ById('togChatGlo').value;
				ById('togChatGlo').style.backgroundColor=ById('togChatGlo').value;
			}, false);
			ById('togChatGloFont').addEventListener('change', function(){
				Colors.ChatGloFont = ById('togChatGloFont').value;
				ById('togChatGloFont').style.backgroundColor=ById('togChatGloFont').value;
			}, false);
			ById('togChatAlliance').addEventListener('change', function(){
				Colors.ChatAlliance = ById('togChatAlliance').value;
				ById('togChatAlliance').style.backgroundColor=ById('togChatAlliance').value;
			}, false);
			ById('togChatAllianceFont').addEventListener('change', function(){
				Colors.ChatAllianceFont = ById('togChatAllianceFont').value;
				ById('togChatAllianceFont').style.backgroundColor=ById('togChatAllianceFont').value;
			}, false);
			if (couleur!="") {
				ById('pcalertHQ').style.background="red";
			}

			ById('boWideOpt').addEventListener ('change', t.e_wideChanged, false);

			ById('togEnableBrowserBG').addEventListener ('change', function(){
				GlobalOptions.enableBrowserBG = ById('togEnableBrowserBG').checked;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);
			ById('pbsendmeaway').addEventListener ('click', function(){
				GlobalOptions.pbNoMoreKabam = ById('pbsendmeaway').checked;
				GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
			},false);

			ById('KsWatchEnable').addEventListener ('change', t.e_watchChanged, false);
			ById('selectprivacymode').addEventListener ('change', function(){
				GlobalOptions.autoPublishPrivacySetting = ById('selectprivacymode').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);

			ById('PubReq').addEventListener ('change', function(){
				GlobalOptions.autoPublishGamePopups = ById('PubReq').checked;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);

			ById('KsResetALL').addEventListener ('click', function(){
				var serverID = getServerId();
				RemoveList = (GM_listValues());
				for (i=0;i<RemoveList.length;i++){
					GM_deleteValue(RemoveList[i]);
				}
				ResetAll=true;
				reloadKOC();
			},false);

			ById('ResetALL').addEventListener ('click', function(){
				RemoveList = (GM_listValues());
				for (i=0;i<RemoveList.length;i++){
					if (RemoveList[i] == "Colors") GM_deleteValue(RemoveList[i]);
				}
				ResetColors=true;
				reloadKOC();
			},false);
			ById('KsResetDF').addEventListener ('click', function(){
			var serverID = getServerId();
				RemoveList = (GM_listValues());
				for (i=0;i<RemoveList.length;i++){
					if (RemoveList[i] == "DFOptions"+ Seed.player['name'] + "_"+serverID) GM_deleteValue(RemoveList[i]);
				}
				ResetDFOptions=true;
				reloadKOC();
			},false);

			ById('togResetStyleOpt').addEventListener ('click', function(){
				var serverID = getServerId();
				RemoveList = (GM_listValues());
				for (i=0;i<RemoveList.length;i++){

					if (RemoveList[i] == "TabOptions_"+serverID) GM_deleteValue(RemoveList[i]);
				}
				ResetTabOptions=true;
				reloadKOC();
			},false);
			ById('optFoodChatHours').addEventListener ('change', function () {
				var x = ById('optFoodChatHours').value;
				if (isNaN(x) || x<0.01 || x>99999){
					ById('optFoodChatHours').value = Options.foodChatWarnHours;
					return;
				}
				Options.foodChatWarnHours = x;
				saveOptions();
			}, false);
			ById('pbLang').addEventListener ('change', function () {
				LangOptions.culang = this.options[this.selectedIndex].text ;
				saveLangOptions();
				reloadKOC();
			}, false);
			ById('KsselectScreenMode').addEventListener ('change', function(){
				GlobalOptions.pbWideScreenStyle = ById('KsselectScreenMode').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);
			ById('KsBackgroundColor').addEventListener ('change', function(){
				GlobalOptions.bgCol = ById('KsBackgroundColor').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
				ById('KsBackgroundColor').style.backgroundColor=ById('KsBackgroundColor').value;
			},false);
			ById('KsBackgroundImage').addEventListener ('change', function(){
				GlobalOptions.bgImg = ById('KsBackgroundImage').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);
			ById('KsBackSelector').addEventListener ('change', function(){
				GlobalOptions.backStyle = ById('KsBackSelector').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);
			ById('KsUpdateChatNoteSel').addEventListener ('change', function(){
				GlobalOptions.updateChatNote = ById('KsUpdateChatNoteSel').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);

				if (Options.alertSound.soundUrlST == 1) 
					var s = SOUND_REDALERT;
				else 
					var s = Options.alertSound.soundUrl;
			t.mss = new Sound(s, t.e_soundFileLoaded);
			t.volSlider = new SliderBar (ById('boVolSlider'), 200, 21, 0);
			t.volSlider.setChangeListener(t.e_volChanged);
			t.volSlider.setValue(Options.alertSound.volume/100);
			t.mss.set('volume', Options.alertSound.volume/100);			
			
			//uW.matSimpleSound01 = t.mss;		

			ById('KsPlayNow').addEventListener ('click', function (){t.playSound(false)}, false);
			ById('optionsSoundStop').addEventListener ('click', t.stopSoundAlerts, false);

			ById('KsSoundRepeat').addEventListener ('change', function (e){Options.alertSound.repeat = e.target.checked}, false);
			ById('KsSoundEvery').addEventListener ('change', function (e){Options.alertSound.repeatDelay = e.target.value}, false);
			ById('KsSoundLength').addEventListener ('change', function (e){Options.alertSound.playLength = e.target.value}, false);
			ById('ksSoundEnable').addEventListener ('change', function (e){Options.alertSound.enabled = e.target.checked}, false);

			ById('optionsSoundStop').disabled = true;
			ById('bosoundFile').addEventListener ('change', function (){
				Options.alertSound.soundUrl = ById('bosoundFile').value;
				if (Options.alertSound.soundUrlST == 1) 
					var s = SOUND_REDALERT;
				else 
					var s = Options.alertSound.soundUrl;
				t.mss = new Sound(s, t.e_soundFileLoaded);
				t.mss.set('volume', Options.alertSound.volume/100);	
			}, false);
			ById('boSoundDefault').addEventListener ('click', function (){
				ById('bosoundFile').value = DEFAULT_ALERT_SOUND_URL;
				Options.alertSound.soundUrl = DEFAULT_ALERT_SOUND_URL;
				saveOptions();
				if (Options.alertSound.soundUrlST == 1) 
					var s = SOUND_REDALERT;
				else 
					var s = Options.alertSound.soundUrl;
				t.mss = new Sound(s, t.e_soundFileLoaded);
				t.mss.set('volume', Options.alertSound.volume/100);	
				
			}, false);
			ById("sUrlST").addEventListener ('click', function () {
				var e = ById("sUrlST");
				if (e.checked) {
					ById('bosoundFile').disabled = true;
					Options.alertSound.soundUrlST = 1;
				} else {
					ById('bosoundFile').disabled = false;
					Options.alertSound.soundUrlST = 0;
				}
				saveOptions();
				if (Options.alertSound.soundUrlST == 1) 
					var s = SOUND_REDALERT;
				else 
					var s = Options.alertSound.soundUrl;
				t.mss = new Sound(s, t.e_soundFileLoaded);
				t.mss.set('volume', Options.alertSound.volume/100);	
			}, false);
			t.togOpt ('KsLangFlag', 'pdxLangFlag');
			t.togOpt ('KsHyperlinks', 'pdxHyperlinks');
			t.togOpt ('KsgmtClock', 'gmtClock', gmtClock.setEnable);
			t.togOpt ('DelRules', 'ChatRules');
			t.togOpt ('togSelQG', 'SelQG');
			t.togOpt ('KsSmiley', 'Smiley');
			t.togOpt ('togDeleteButtons', 'deleteButtons');
			t.togOpt ('togmerlinClose', 'merlinClose');
			t.togOpt ('pbTresureChestFB', 'TresureChestFB');
			t.togOpt ('KsChatLeader', 'ChatLearder');
			t.togOpt ('togPDXMenuLeft', 'pdxMenuLeft');
			t.togOpt ('togPostMultiUpdate', 'postMultiUpdate');
			t.togOpt ('togShowMultiUpdateNote', 'showMultiUpdateNote');
			t.togOpt ('pbGoldEnable', 'pbGoldEnable', CollectGold.setEnable);
			t.togOpt ('togKsBadge', 'showKsBadge');
			t.togOpt ('togmovementopen', 'tabmovementopen');
			t.changeOpt ('pbgoldLimit', 'pbGoldHappy');
			t.changeOpt ('togcolorUserName1', 'userName1'); t.changeOpt ('togcolorUserName2', 'userName2'); t.changeOpt ('togcolorUserName3', 'userName3'); t.changeOpt ('togcolorUserName4', 'userName4'); t.changeOpt ('togcolorUserName5', 'userName5'); t.changeOpt ('togcolorUserName6', 'userName6'); t.changeOpt ('togcolorUserName7', 'userName7'); t.changeOpt ('togcolorUserName8', 'userName8'); t.changeOpt ('togcolorUserName9', 'userName9'); t.changeOpt ('togcolorUserName10', 'userName10'); t.changeOpt ('togcolorUserName11', 'userName11'); t.changeOpt ('togcolorUserName12', 'userName12'); t.changeOpt ('togcolorUserName13', 'userName13'); t.changeOpt ('togcolorUserName14', 'userName14'); t.changeOpt ('togcolorUserName15', 'userName15'); t.changeOpt ('togcolorUserName16', 'userName16'); t.changeOpt ('togcolorUserName17', 'userName17'); t.changeOpt ('togcolorUserName18', 'userName18'); t.changeOpt ('togcolorUserName19', 'userName19'); t.changeOpt ('togcolorUserName20', 'userName20'); t.changeOpt ('togcolorUserName21', 'userName21'); t.changeOpt ('togcolorUserName22', 'userName22'); t.changeOpt ('togcolorUserName23', 'userName23'); t.changeOpt ('togcolorUserName24', 'userName24'); t.changeOpt ('togcolorUserName25', 'userName25'); t.changeOpt ('togcolorUserName26', 'userName26'); t.changeOpt ('togcolorUserName27', 'userName27'); t.changeOpt ('togcolorUserName28', 'userName28'); t.changeOpt ('togcolorUserName29', 'userName29');	t.changeOpt ('togcolorUserName30', 'userName30');
			t.togOpt ('ptEnableUserName1', 'enableUserName1'); t.togOpt ('ptEnableUserName2', 'enableUserName2'); t.togOpt ('ptEnableUserName3', 'enableUserName3'); t.togOpt ('ptEnableUserName4', 'enableUserName4'); t.togOpt ('ptEnableUserName5', 'enableUserName5'); t.togOpt ('ptEnableUserName6', 'enableUserName6'); t.togOpt ('ptEnableUserName7', 'enableUserName7'); t.togOpt ('ptEnableUserName8', 'enableUserName8'); t.togOpt ('ptEnableUserName9', 'enableUserName9'); t.togOpt ('ptEnableUserName10', 'enableUserName10');	t.togOpt ('ptEnableUserName11', 'enableUserName11'); t.togOpt ('ptEnableUserName12', 'enableUserName12'); t.togOpt ('ptEnableUserName13', 'enableUserName13'); t.togOpt ('ptEnableUserName14', 'enableUserName14'); t.togOpt ('ptEnableUserName15', 'enableUserName15'); t.togOpt ('ptEnableUserName16', 'enableUserName16'); t.togOpt ('ptEnableUserName17', 'enableUserName17'); t.togOpt ('ptEnableUserName18', 'enableUserName18'); t.togOpt ('ptEnableUserName19', 'enableUserName19'); t.togOpt ('ptEnableUserName20', 'enableUserName20'); t.togOpt ('ptEnableUserName21', 'enableUserName21'); t.togOpt ('ptEnableUserName22', 'enableUserName22'); t.togOpt ('ptEnableUserName23', 'enableUserName23'); t.togOpt ('ptEnableUserName24', 'enableUserName24'); t.togOpt ('ptEnableUserName25', 'enableUserName25'); t.togOpt ('ptEnableUserName26', 'enableUserName26'); t.togOpt ('ptEnableUserName27', 'enableUserName27'); t.togOpt ('ptEnableUserName28', 'enableUserName28'); t.togOpt ('ptEnableUserName29', 'enableUserName29'); t.togOpt ('ptEnableUserName30', 'enableUserName30');
			t.changeColors ('toguserBG1', 'userBG1'); t.changeColors ('toguserBG2', 'userBG2'); t.changeColors ('toguserBG3', 'userBG3'); t.changeColors ('toguserBG4', 'userBG4'); t.changeColors ('toguserBG5', 'userBG5'); t.changeColors ('toguserBG6', 'userBG6'); t.changeColors ('toguserBG7', 'userBG7'); t.changeColors ('toguserBG8', 'userBG8'); t.changeColors ('toguserBG9', 'userBG9'); t.changeColors ('toguserBG10', 'userBG10'); t.changeColors ('toguserBG11', 'userBG11'); t.changeColors ('toguserBG12', 'userBG12'); t.changeColors ('toguserBG13', 'userBG13'); t.changeColors ('toguserBG14', 'userBG14'); t.changeColors ('toguserBG15', 'userBG15'); t.changeColors ('toguserBG16', 'userBG16'); t.changeColors ('toguserBG17', 'userBG17'); t.changeColors ('toguserBG18', 'userBG18'); t.changeColors ('toguserBG19', 'userBG19'); t.changeColors ('toguserBG20', 'userBG20'); t.changeColors ('toguserBG21', 'userBG21'); t.changeColors ('toguserBG22', 'userBG22'); t.changeColors ('toguserBG23', 'userBG23'); t.changeColors ('toguserBG24', 'userBG24'); t.changeColors ('toguserBG25', 'userBG25'); t.changeColors ('toguserBG26', 'userBG26'); t.changeColors ('toguserBG27', 'userBG27'); t.changeColors ('toguserBG28', 'userBG28'); t.changeColors ('toguserBG29', 'userBG29');	t.changeColors ('toguserBG30', 'userBG30');	
			t.togOpt ('togKsFunSoundAttack', 'KsFunSoundAttack');	t.togOpt ('togKsFunSoundHorn', 'KsFunSoundHorn');	t.togOpt ('togKsFunSoundGun', 'KsFunSoundGun');
			t.changeOpt ('togURLF1', 'soundURLF1');	
			t.changeOpt ('togURLF1vol', 'URLsonF1vol');	
			t.changeOpt ('togURLF2', 'soundURLF2');	
			t.changeOpt ('togURLF2vol', 'URLsonF2vol');	
			t.changeOpt ('togURLF3', 'soundURLF3');	
			t.changeOpt ('togURLF3vol', 'URLsonF3vol');	
			t.changeOpt ('togKsRPClip', 'RPClip');
			t.changeStyleOpt ('KsToOverview', 'toOverview');
			t.changeStyleOpt ('KsToReports', 'toReports');
			t.changeStyleOpt ('KsToMarches', 'toMarches');
			t.changeStyleOpt ('KsToSendMarches', 'toSendMarch');
			t.changeStyleOpt ('KsToTrain', 'toTrain');
			t.changeStyleOpt ('KsToAutoTrain', 'toAutoTrain');
			t.changeStyleOpt ('KsToPopControl', 'toPopControl');
			t.changeStyleOpt ('KsToThroneStuff', 'toThroneStuff');
			t.changeStyleOpt ('KsToSearch', 'toSearch');
			t.changeStyleOpt ('KsToTurboSearch', 'toTurboSearch');
			t.changeStyleOpt ('KsToPlayer', 'toPlayer');
			t.changeStyleOpt ('KsToBuild', 'toBuild');
			t.changeStyleOpt ('KsToTransport', 'toTransport');
			t.changeStyleOpt ('KsToReassign', 'toReassign');
			t.changeStyleOpt ('KsToAutoCraft', 'toAutoCraft');
			t.changeStyleOpt ('KsToFarm', 'toFarm');
			t.changeStyleOpt ('KsToCrest', 'toCrest');
			t.changeStyleOpt ('KsToDarkForest', 'toDarkForest');
			t.changeStyleOpt ('KsToAttackTab', 'toAttackTab');
			t.changeStyleOpt ('KsToRaid', 'toRaid');
			t.changeStyleOpt ('KsToApothecary', 'toApothecary');
			t.changeStyleOpt ('KsToScoutAlliance', 'toScoutAlliance');
			t.changeStyleOpt ('KsToWild', 'toWild');
			t.changeStyleOpt ('KsToKnights', 'toKnights');
			t.changeStyleOpt ('KsToOptions', 'toOptions');
			t.changeStyleOpt ('KsToUserTab', 'toUserTab');
			t.changeStyleOpt ('KsToKoCScripts', 'toKoCScripts');

			t.togOpt ('togAllMembers', 'enhanceViewMembers', AllianceReports.enable_viewmembers);
			t.togOpt ('ptEnableFoodWarnTchat', 'enableFoodWarnTchat', FoodAlerts.init);
			t.togOpt ('ptAllowWinMove', 'ptWinDrag', mainPop.setEnableDrag);
			t.togOpt ('ptAllowTransparent', 'KsTransparence');
			t.togOpt ('ptEnableFoodWarn', 'enableFoodWarn');
			t.togOpt ('togChatStuff', 'chatEnhance', ChatStuff.setEnable, ChatStuff.isAvailable);
			t.togOpt ('togKnightSelect', 'fixKnightSelect', AttackDialog.setEnable, AttackDialog.isKnightSelectAvailable);
			t.togOpt ('togAttackPicker', 'attackCityPicker', AttackDialog.setEnable, AttackDialog.isCityPickerAvailable);
			t.togOpt ('togEnhanceMsging', 'enhanceMsging', messageNav.setEnable, messageNav.isAvailable);
			t.togOpt ('togCoordBox', 'mapCoordsTop', CoordBox.setEnable, CoordBox.isAvailable);
			t.togOpt ('togMightKoCBugFix', 'showMightKoCBugFix');
			t.togOpt ('togResKoCBugFix', 'showResKoCBugFix');
			t.togOpt ('togKsInfoBox', 'showKsInfoBox');
			t.togOpt ('togWWclick', 'WWclick');
			t.togOpt ('togMultiBrowser', 'MultiBrowser');
			//t.togOpt ('togAntiCheat', 'pbAntiCheat');
			t.togOpt ('togWhisperOn', 'WhisperOn');
			t.togOpt ('togAttaqueOn', 'AttaqueOn');
			t.togOpt ('togWildSoundOn', 'WildSoundOn');
			t.togOpt ('togFoodSoundOn', 'FoodSoundOn');
			t.togOpt ('togEclaireurOn', 'EclaireurOn');
			t.togOpt ('user_icon', 'icon_chat');
			t.togOpt ('user_iconFlag', 'icon_chatFlag');
			t.togOpt ('MapExtra', 'MapShowExtra');
			t.togOpt ('deletetoggle', 'DeleteMsg');
			t.togOpt ('delete4toggle', 'DeleteMsgs4');
			t.togOpt ('deletes5toggle', 'DeleteMsgs5');
			t.togOpt ('deletes6toggle', 'DeleteMsgs6');
			t.togOpt ('deletes0toggle', 'DeleteMsgs0');
			t.togOpt ('deletes1toggle', 'DeleteMsgs1');
			t.togOpt ('deletes2toggle', 'DeleteMsgs2');
			t.togOpt ('deletes3toggle', 'DeleteMsgs3');
			t.togOpt ('HelReq', 'HelpRequest');
			t.togOpt ('DelReq', 'DeleteRequest');
			t.togOpt ('togEnableButtler', 'enableButtler');
			t.togOpt ('KsSummonToggle', 'KsSummonToggle');
			t.changeOpt ('pbeverymins', 'pbEveryMins' , RefreshEvery.setTimer);
			ById('togCustomWideScreenSize').addEventListener ('change', function(){
				GlobalOptions.customWideScreenSize = ById('togCustomWideScreenSize').value;
				GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
			},false);
			
			//Speedups
			for (var i=1; i<=10; i++) {
				if (i==9) continue;
				t.togOpt ('pbusespeedup'+i, 'speed'+i);
			}
			
			//t.changeOpt ('togCustomWideScreenSize', 'customWideScreenSize');
			t.togOpt ('pbEveryEnable', 'pbEveryEnable', RefreshEvery.setEnable);
			t.togOpt ('pbRefreshSeed', 'RefreshSeed');
			t.changeOpt ('pbRefreshSeedInterval', 'RefreshSeedInterval');
			t.togOpt ('pbChatREnable', 'pbChatOnRight', WideScreen.setChatOnRight);
			t.togOpt ('pbWMapEnable', 'pbWideMap', WideScreen.useWideMap);
			t.togOpt ('togAllRpts', 'enhanceARpts', AllianceReports.enable);
			ById('pcalertEnable').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pbalertDefend').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertPrefix').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertQG').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertScout').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertWild').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertTroops').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertTroops2').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertEmbassy').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertFletching').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertMarechal').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertdefBoost').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertMytroops').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertFood').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertDefense').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertHQ').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertSendAsWhisper').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertSendToAlly').addEventListener ('change', t.e_alertOptChanged, false);
			ById('Ksalertraid').addEventListener ('change', t.e_alertOptChanged, false);
			ById('Ksalertautofo').addEventListener ('change', t.e_alertOptChanged, false);
			ById('Ksalertautots').addEventListener ('change', t.e_alertOptChanged, false);
			ById('Ksalertappro').addEventListener ('change', t.e_alertOptChanged, false);
			ById('Ksalertemail').addEventListener ('change', t.e_alertOptChanged, false);

			ById('pcalertTroneRange').addEventListener ('change', t.e_alertOptChanged, false);
			ById('pcalertTroneRangeDebuff').addEventListener ('change', t.e_alertOptChanged, false);
			
			ById('Ksalertthrone').addEventListener ('change', t.e_alertOptChanged, false);
			ById('KsalertTSet').value = Options.alertConfig.throneSet;
			ById('KsalertTSet').addEventListener ('change', t.e_alertOptChanged, false);
			ById('KsalertthroneRet').addEventListener ('change', t.e_alertOptChanged, false);		
			ById('KsalertTSetRet').value = Options.alertConfig.throneSetRet;
			ById('KsalertTSetRet').addEventListener ('change', t.e_alertOptChanged, false);
			ById('KsalertthroneMin').addEventListener ('change', t.e_alertOptChanged, false);

			ById('Ksdeletetimer').addEventListener ('change', function () {
				if (parseInt(ById('Ksdeletetimer').value) < 2) {
					ById('Ksdeletetimer').value=2;
				}
				Options.DeleteTimerMinute = ById('Ksdeletetimer').value;
				saveOptions();
			}, false);

			t.changeOpt ('togURL1', 'URLson1');
			t.changeOpt ('togURLson1Vol', 'URLson1Vol');
			t.changeOpt ('KspopupBorderRadius', 'popupBorderRadius');
			t.changeOpt ('togURL2', 'URLson2');
			t.changeOpt ('togURLson2Vol', 'URLson2Vol');
			t.changeOpt ('togURL4', 'URLson4');
			t.changeOpt ('togURLson4Vol', 'URLson4Vol');
			t.changeOpt ('togURL5', 'URLson5');
			t.changeOpt ('togURLson5Vol', 'URLson5Vol');
			t.changeOpt ('togURL6', 'URLson6');
			t.changeOpt ('togURLson6Vol', 'URLson6Vol');
			t.changeOpt ('togURL3', 'URLicon3');
			t.changeOpt ('togMultiUpdateSoundEnable', 'multiUpdateSoundEnable');
			t.changeOpt ('togMultiUpdateSoundVol', 'multiUpdateSoundVol');

			ById("KsDefURL3").addEventListener ('click', function () {
				Options.URLicon3 = 'http://kofc.god-like.info/multi/img/pdx-useravatar.png';
				ById('togURL3').value='http://kofc.god-like.info/multi/img/pdx-useravatar.png';
				saveOptions();
			}, false);

			ById("KsDefURL1").addEventListener ('click', function () {
				Options.URLson1 = 'https://koc-power-pdx.googlecode.com/files/sonar.ogg';
				ById('togURL1').value='https://koc-power-pdx.googlecode.com/files/sonar.ogg';
				saveOptions();
			}, false);
			ById("KsDefURL2").addEventListener ('click', function () {
				Options.URLson2 = 'https://koc-power-pdx.googlecode.com/files/alarm.ogg';
				ById('togURL2').value='https://koc-power-pdx.googlecode.com/files/alarm.ogg';
				saveOptions();
			}, false);
			ById("KsDefURL4").addEventListener ('click', function () {
				Options.URLson4 = 'https://koc-power-pdx.googlecode.com/files/ding.ogg';
				ById('togURL4').value='https://koc-power-pdx.googlecode.com/files/ding.ogg';
				saveOptions();
			}, false);
			ById("KsDefURL5").addEventListener ('click', function () {
				Options.URLson5 = 'https://koc-power-pdx.googlecode.com/files/slap.ogg';
				ById('togURL5').value='https://koc-power-pdx.googlecode.com/files/slap.ogg';
				saveOptions();
			}, false);
			ById("KsDefURL6").addEventListener ('click', function () {
				Options.URLson6 = 'https://koc-power-pdx.googlecode.com/files/cartoon.ogg';
				ById('togURL6').value='https://koc-power-pdx.googlecode.com/files/cartoon.ogg';
				saveOptions();
			}, false);
			ById("PDXDefURLF1").addEventListener ('click', function () {
				Options.soundURLF1 = 'https://koc-power-pdx.googlecode.com/files/siren.ogg';
				ById('togURLF1').value='https://koc-power-pdx.googlecode.com/files/siren.ogg';
				saveOptions();
			}, false);
			ById("PDXDefURLF2").addEventListener ('click', function () {
				Options.soundURLF2 = 'https://koc-power-pdx.googlecode.com/files/horn.ogg';
				ById('togURLF2').value='https://koc-power-pdx.googlecode.com/files/horn.ogg';
				saveOptions();
			}, false);
			ById("PDXDefURLF3").addEventListener ('click', function () {
				Options.soundURLF3 = 'https://koc-power-pdx.googlecode.com/files/gunshot.ogg';
				ById('togURLF3').value='https://koc-power-pdx.googlecode.com/files/gunshot.ogg';
				saveOptions();
			}, false);
			ById("stURL1").addEventListener ('click', function () {
				var e = ById("stURL1");
				if (e.checked) {
					ById('togURL1').disabled = true;
					Options.URLson1ST = 1;
				} else {
					ById('togURL1').disabled = false;
					Options.URLson1ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURL2").addEventListener ('click', function () {
				var e = ById("stURL2");
				if (e.checked) {
					ById('togURL2').disabled = true;
					Options.URLson2ST = 1;
				} else {
					ById('togURL2').disabled = false;
					Options.URLson2ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURL4").addEventListener ('click', function () {
				var e = ById("stURL4");
				if (e.checked) {
					ById('togURL4').disabled = true;
					Options.URLson4ST = 1;
				} else {
					ById('togURL4').disabled = false;
					Options.URLson4ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURL5").addEventListener ('click', function () {
				var e = ById("stURL5");
				if (e.checked) {
					ById('togURL5').disabled = true;
					Options.URLson5ST = 1;
				} else {
					ById('togURL5').disabled = false;
					Options.URLson5ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURL6").addEventListener ('click', function () {
				var e = ById("stURL6");
				if (e.checked) {
					ById('togURL6').disabled = true;
					Options.URLson6ST = 1;
				} else {
					ById('togURL6').disabled = false;
					Options.URLson6ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURLF1").addEventListener ('click', function () {
				var e = ById("stURLF1");
				if (e.checked) {
					ById('togURLF1').disabled = true;
					Options.URLsonF1ST = 1;
				} else {
					ById('togURLF1').disabled = false;
					Options.URLsonF1ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURLF2").addEventListener ('click', function () {
				var e = ById("stURLF2");
				if (e.checked) {
					ById('togURLF2').disabled = true;
					Options.URLsonF2ST = 1;
				} else {
					ById('togURLF2').disabled = false;
					Options.URLsonF2ST = 0;
				}
				saveOptions();
			}, false);
			ById("stURLF3").addEventListener ('click', function () {
				var e = ById("stURLF3");
				if (e.checked) {
					ById('togURLF3').disabled = true;
					Options.URLsonF3ST = 1;
				} else {
					ById('togURLF3').disabled = false;
					Options.URLsonF3ST = 0;
				}
				saveOptions();
			}, false);
			
			//Sounds direkt abspielen
			ById("KsPlayNow1").addEventListener ('click', function () {
				if (Options.URLson1ST == 1) 
					var s = SOUND_SONAR;
				else 
					var s = Options.URLson1;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLson1Vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNow4").addEventListener ('click', function () {
				if (Options.URLson4ST == 1) 
					var s = SOUND_DING;
				else 
					var s = Options.URLson4;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLson4Vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNow2").addEventListener ('click', function () {
				if (Options.URLson2ST == 1) 
					var s = SOUND_ALARM;
				else 
					var s = Options.URLson2;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLson2Vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNow5").addEventListener ('click', function () {
				if (Options.URLson5ST == 1) 
					var s = SOUND_SLAP;
				else 
					var s = Options.URLson5;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLson5Vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNow6").addEventListener ('click', function () {
				if (Options.URLson6ST == 1) 
					var s = SOUND_CARTOON;
				else 
					var s = Options.URLson6;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLson6Vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNowF1").addEventListener ('click', function () {
				if (Options.URLsonF1ST == 1) 
					var s = SOUND_SIREN;
				else 
					var s = Options.soundURLF1;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLsonF1vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNowF2").addEventListener ('click', function () {
				if (Options.URLsonF2ST == 1) 
					var s = SOUND_HORN;
				else 
					var s = Options.soundURLF2;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLsonF2vol/100);
					faudio.play();
				});
			}, false);
			
			ById("KsPlayNowF3").addEventListener ('click', function () {
				if (Options.URLsonF3ST == 1) 
					var s = SOUND_GUNSHOT;
				else 
					var s = Options.soundURLF3;
				var faudio = new Sound(s, function() {
					faudio.set('volume', Options.URLsonF3vol/100);
					faudio.play();
				});
			}, false);
			
			ById('optHauteurBoite').addEventListener ('change', function () {
				var x = ById('optHauteurBoite').value;
				if (isNaN(x) || x<600 || x>1000){
					ById('optHauteurBoite').value = 700;
				}
				Options.HauteurBoite = x;
				saveOptions();
			}, false);

			var checkbox = ById('togEnhanceMsging');
			if (Options.enhanceMsging)
				checkbox.checked = true;
			checkbox.addEventListener ('change', function (){messageNav.setEnable(ById('togEnhanceMsging').checked)}, false);

		} catch (e) {
			t.cont.innerHTML = '<PRE>'+ e.name +': '+ e.message +'</pre>';
		}

	},
	doImport: function (){
      var t = Tabs.Options;
      var serverID = getServerId();
      // var Data = JSON2.parse(document.getElementById('pbImportData').value);
      // if (Data.TransportOptions != {}) Tabs.Transport.tradeRoutes = Data.TransportOptions;
      // Tabs.Transport.saveTradeRoutes();
      // if (Data.TransportState != {}) Tabs.Transport.traderState = Data.TransportState;
      // Tabs.Transport.saveTraderState();
      if (Data.ReassignRoutes != {}) Tabs.Reassign.reassignRoutes = Data.ReassignRoutes;
      Tabs.Reassign.saveReassignRoutes();
      // for (i=0;i<Seed.cities.length;i++) if (Data["Build" + (i+1)].length > 0) Tabs.build["bQ_" + Seed.cities[i][0]] = Data["Builds" + (i+1)];
      if (Data.Options != {}) Options = Data.Options;
      saveOptions();
      if (Data.GlobalOptions != {}) GlobalOptions = Data.GlobalOptions;
      GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
      if (Data.ThroneOptions != {}) ThroneOptions = Data.ThroneOptions;
      saveThroneOptions();
      if (Data.TrainOptions != {}) TrainOptions = Data.TrainOptions;
      saveTrainOptions();
      if (Data.ApothecaryOptions != {}) ApothecaryOptions = Data.ApothecaryOptions;
      if (Data.FarmOptions != {}) FarmOptions = Data.FarmOptions;
      saveFarmOptions();
      if (Data.MarchOptions != {}) MarchOptions = Data.MarchOptions;
      saveMarchOptions();
      if (Data.Colors != {}) Colors = Data.Colors;
      saveColors();
      // if (Data.ChatIcons != {}) ChatIcons = Data.ChatIcons;
      // saveChatIcons();
      // if (Data.CraftOptions != {}) CraftOptions = Data.CraftOptions;
      // saveCraftOptions();
      if (Data.AtkOptions != {}) AtkOptions = Data.AtkOptions;
      saveAtkOptions();
      if (Data.DFOptions != {}) DFOptions = Data.DFOptions;
      saveDFOptions();
      // if (Data.CrestOptions != {}) CrestOptions = Data.CrestOptions;
      // saveCrestOptions();
      reloadKOC();    
    },
    doExport: function (){
      var t = Tabs.Options;
      var serverID = getServerId();
      // for (i=0;i<Seed.cities.length;i++) t.Data["Build" + (i+1)] = JSON2.parse(GM_getValue('bQ_' + serverID + '_' + Seed.cities[i][0]));
      // t.Data.TransportOptions = Tabs.Transport.tradeRoutes;
      // t.Data.TransportState = Tabs.Transport.traderState
      t.Data.Options = Options;
      t.Data.GlobalOptions = GlobalOptions;
      t.Data.ThroneOptions = ThroneOptions;
      // t.Data.CrestOptions = CrestOptions;
      t.Data.TrainOptions = TrainOptions;
      t.Data.DFOptions = DFOptions;
      t.Data.ApothecaryOptions = ApothecaryOptions;
      t.Data.FarmOptions = FarmOptions;
      t.Data.MarchOptions = MarchOptions;
      t.Data.ReassignRoutes = Tabs.Reassign.reassignRoutes;
      t.Data.Colors = Colors;
      // t.Data.ChatIcons = ChatIcons;
      // t.Data.CraftOptions = CraftOptions;
      t.Data.AtkOptions = AtkOptions;
      ById('pbImportData').value = JSON2.stringify(t.Data);
      ById('pbImportData').select();
    },
  
	EmoClick: function(what) {
		ById ("mod_comm_input").value += " " + what + " ";
	},
	EmoHelp : function (){
		var t = Tabs.Options;
		uW.KsEmoClick = t.EmoClick;
		var helpText = '<DIV style="max-height:400px;">';
		helpText += '<TABLE width=98% cellspacing=0 cellpadding=2 border=0 bordercolor=black class=pdxTab><tr>';
		var row=0;
		for (k in Smileys) {
			helpText += '<TR><TD><img class=emoicon src=\"'+Smileys[k]+'\" onclick="KsEmoClick(\''+k+'\')"></td><TD><font size=1>'+k+'</td></tr>';
		}
		helpText += '</table></div>';

		var inputtext=ById('mod_comm_input');
		var pop = new CPopup ('EmoHelp', 0, 0, 115, 455, true);
		pop.getMainDiv().innerHTML = helpText;
		pop.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.mainSmileys+'</div>';
		pop.show (true);

		ById("EmoHelp_outer").style.top = (getOffset(inputtext).top+30) +'px';
		ById("EmoHelp_outer").style.left = (getOffset(inputtext).left+230) +'px';
	},

	hide : function (){
	},
	loadUrl : function (url){
		var t = Tabs.Options;
    t.mss.load(url, t.e_soundFileLoaded);
		ById('optionsLoadSWF').innerHTML = ''+culang.optionsChargement+'';
	},
	e_swfLoaded : function (){
		var t = Tabs.Options;
		ById('boSoundOpts').style.display = 'inline';
		t.volSlider.setValue (Options.alertSound.volume/100);
		t.loadUrl (Options.alertSound.soundUrl);
		if (Options.alertSound.alarmActive && Options.alertSound.expireTime>unixTime())   {
			t.soundTheAlert();
		}
	},
	e_volChanged : function (val){
		var t = Tabs.Options;
		ById('boVolOut').innerHTML = parseInt(val*100);
		Options.alertSound.volume = parseInt(val*100);
    t.mss.set('volume', Options.alertSound.volume/100);
	},
changeColors : function (valueId, optionName, callOnChange){
    var t = Tabs.Options;
    var e = document.getElementById(valueId);
    e.value = Colors[optionName];
    e.addEventListener ('change', eventHandler, false);
    function eventHandler (){
      Colors[optionName] = this.value;
      saveColors();
      if (callOnChange)
        callOnChange (this.value);
    }
  },
	togOpt : function (checkboxId, optionName, callOnChange){
		var t = Tabs.Options;
		var checkbox = ById(checkboxId);
		if (Options[optionName])
			checkbox.checked = true;
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (callOnChange)
				callOnChange (this.checked);

			if (optionName=="DeleteMsgs5" || optionName=="DeleteMsgs6" || "DeleteMsgs4" || optionName=="DeleteMsg" || optionName=="DeleteMsgs0" || optionName=="DeleteMsgs1" || optionName=="DeleteMsgs2" || optionName=="DeleteMsgs3") {
				DeleteReports.init();
			}
		}
	},
	changeOpt : function (valueId, optionName, callOnChange){
		var t = Tabs.Options;
		var e = ById(valueId);
		e.value = Options[optionName];
		e.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			if (optionName == "RefreshSeedInterval" && parseInt(this.value) < 15) this.value = 15;
			if (optionName == "RefreshSeedInterval" && parseInt(this.value) > 300) this.value = 300;
			Options[optionName] = this.value;
			saveOptions();
			if (callOnChange)
				callOnChange (this.value);
		}
	},

	changeStyleOpt : function (valueId, optionName, callOnChange){
		var t = Tabs.Options;
		var e = ById(valueId);
		e.value = TabOptions[optionName];
		e.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			TabOptions[optionName] = this.value;
			saveTabOptions();
			if (callOnChange)
				callOnChange (this.value);
		}
	},
	saveCategorys:function(tab) {
		ById(tab).style.display=(ById(tab).style.display=='none')?'block':'none';
		Options[tab]=ById(tab).style.display;
		saveOptions();
	},
	e_watchChanged : function (){
		GlobalOptions.pbWatchdog = ById('KsWatchEnable').checked;
		GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
	},
	e_wideChanged : function (){
		GlobalOptions.pbWideScreen = ById('boWideOpt').checked;
		GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
	},

	e_alertOptChanged : function (){
		Options.alertConfig.aChat = ById('pcalertEnable').checked;
		Options.alertConfig.aPrefix=ById('pcalertPrefix').value;
		Options.alertConfig.scouting=ById('pcalertScout').checked;
		Options.alertConfig.wilds=ById('pcalertWild').checked;
		Options.alertConfig.MonQG=ById('pcalertQG').checked;
		Options.alertConfig.embassy=ById('pcalertEmbassy').checked;
		Options.alertConfig.fletching=ById('pcalertFletching').checked;
		Options.alertConfig.marechal=ById('pcalertMarechal').checked;
		Options.alertConfig.defBoost=ById('pcalertdefBoost').checked;
		Options.alertConfig.mytroops=ById('pcalertMytroops').checked;
		Options.alertConfig.food=ById('pcalertFood').checked;
		Options.alertConfig.defense=ById('pcalertDefense').checked;
		Options.alertConfig.defence=ById('pbalertDefend').checked;
		Options.alertConfig.hq=ById('pcalertHQ').options[ById('pcalertHQ').selectedIndex].value;
		Options.alertConfig.sendasWhisper=ById('pcalertSendAsWhisper').checked;
		Options.alertConfig.sendtoAlly=ById('pcalertSendToAlly').checked;
		Options.alertConfig.raid=ById('Ksalertraid').checked;
		Options.alertConfig.appro=ById('Ksalertappro').checked;
		Options.alertConfig.autofo=ById('Ksalertautofo').checked;
		Options.alertConfig.autots=ById('Ksalertautots').checked;
		Options.alertConfig.email = ById('Ksalertemail').checked;
		Options.alertConfig.TroneRange=ById('pcalertTroneRange').checked;
		Options.alertConfig.TroneRangeDebuff=ById('pcalertTroneRangeDebuff').checked;
		Options.alertConfig.changeThrone=ById('Ksalertthrone').checked;
		Options.alertConfig.throneSet=ById('KsalertTSet').value;
		if (!Options.alertConfig.changeThrone) {
			ById('KsalertthroneRet').checked = false;
			Options.alertConfig.RecentActivity = false;
		}
		Options.alertConfig.returnThrone=ById('KsalertthroneRet').checked;
		if (!Options.alertConfig.returnThrone) {
			Options.alertConfig.RecentActivity = false;
		}
		Options.alertConfig.throneSetRet=ById('KsalertTSetRet').value;
		Options.alertConfig.returnThroneMin=parseInt(ById('KsalertthroneMin').value);
		var mt = parseInt(ById('pcalertTroops').value);
		if (mt<1 || mt>120000){
			ById('pcalertTroops').value = Options.alertConfig.minTroops;
			ById('pcalerterr').innerHTML = '<font color=#600000><B>'+culang.mainInvalid+'</b></font>';
			setTimeout (function (){ById('pcalerterr').innerHTML =''}, 2000);
			return;
		}
		Options.alertConfig.minTroops = mt;
		var mt = parseInt(ById('pcalertTroops2').value);
		if (mt<1 || mt>120000){
			ById('pcalertTroops2').value = Options.alertConfig.minTroops2;
			ById('pcalerterr').innerHTML = '<font color=#600000><B>'+culang.mainInvalid+'</b></font>';
			setTimeout (function (){ById('pcalerterr').innerHTML =''}, 2000);
			return;
		}
		Options.alertConfig.minTroops2 = mt;
		saveOptions();
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/Raid.js">
//	
//	   KOC POWER - TABS RAID											        
//	


Tabs.Raid = {
	tabDisabled : false,
	tabLabel: culang.mainRaid,
	tabOrder : TabOptions.toRaid,
	myDiv : null,
	rallypointlevel:null,
	knt:{},
	Troops:{},
	city:0,
	raidtimer:null,
	rslt:{},
	save:{},
	stopping:false,
	resuming:false,
	deleting:false,
	stopprogress:0,
	stopcount:0,
	activecount:0,
	count:0,
	timerLookup:null,
	timerPaint:null,
	timerReport:null,

	init : function (div){
		var t = Tabs.Raid;
		t.myDiv = div;
		t.raidtimer = setTimeout(t.checkRaids, 6000);
		var m = '<DIV class=pdxStat>'+culang.raidHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center"><td colspan=2><INPUT id=pbraidtab type=submit value="'+culang.raidStopRaids+'" class="tab"><INPUT id=pbraidtabRes type=submit value="'+culang.raidResumeRaids+'" class="tab" ><INPUT id=pbraidtabDel type=submit value="'+culang.raidDeleteRaids+'" class="tab"></td><TR align="center">';
		m += '<TD><INPUT id=pbRaidStart type=submit value="'+culang.raidAutoReset+' = '+ (Options.RaidRunning?culang.buttonON:culang.buttonOFF) +'" ></td>';
		m += '<TD><INPUT id=pbsendraidreport type=checkbox '+ (Options.foodreport?'CHECKED':'') +'\> '+culang.raidReport+' ';
		m += '<INPUT id=pbsendreportint value='+ Options.MsgInterval +' type=text size=3 \> '+culang.raidReport2+'</td>';
		m += '</tr></table></div>';
		m += '<DIV class=pdxStat>'+culang.raidActiveHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center">';
		m += '<TD><DIV style="margin-bottom:10px;"><span id=ptRaidCity></span></div></td></tr>';
		m+='<TR><TD><DIV style="margin-bottom:10px;"><span id=ptRaidTimer></span></div></td></tr></table>';
		m += '<DIV id=PaintRaids></div>';
		m += '<DIV class=pdxStat>'+culang.raidSavedHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center">';
		m += '<DIV id=SavedRaids></div>';
		t.myDiv.innerHTML = m;
		if (Options.foodreport) {
			t.timerReport=setInterval(t.sendreport, 1*60*1000);
		}

		t.from = new CdispCityPicker ('ptRaidpicker', ById('ptRaidCity'), true, t.clickCitySelect, 0);
		ById('pbRaidStart').addEventListener('click', t.toggleRaidState, false);
		ById('pbsendraidreport').addEventListener('change', function(){
			Options.foodreport = ById('pbsendraidreport').checked;
			if (Options.foodreport) {
				clearInterval(t.timerReport);
				t.timerReport=setInterval(t.sendreport, 1*60*1000);
			} else {
				clearInterval(t.timerReport);
			}
			saveOptions();
		}, false);
		ById('pbsendreportint').addEventListener('change', function(){
			Options.MsgInterval = parseInt(ById('pbsendreportint').value);
			saveOptions();
		}, false);

		ById('pbraidtab').addEventListener('click', t.StopAllRaids, false);
		ById('pbraidtabRes').addEventListener('click', t.ResumeAllRaids, false);
		ById('pbraidtabDel').addEventListener('click', t.DeleteAllRaids, false);


		var serverID = getServerId();
		t.save = GM_getValue ('SavedRaids_'+serverID);
		if (t.save != undefined) t.save = JSON2.parse (t.save);


	},

	lookup : function (){
		var t = Tabs.Raid;
		t.activecount=0;
		t.stopcount=0;
		for (c=0; c< Seed.cities.length;c++) {
			cityID = 'city' + Seed.cities[c][0];
			for (b in Seed.queue_atkp[cityID]){
				destinationUnixTime = Seed.queue_atkp[cityID][b]['destinationUnixTime'];
				MarchStatus = Seed.queue_atkp[cityID][b]['marchStatus'];
				MarchType = Seed.queue_atkp[cityID][b]['marchType'];
				botMarchStatus = Seed.queue_atkp[cityID][b]['botMarchStatus'];
				if (MarchType == 9 &&  MarchStatus == 3 || MarchStatus==10) t.stopcount++;
				else if (MarchType == 9) t.activecount++;

			}
		}

		if (t.resuming == false && t.stopping == false && t.deleting == false && t.activecount != 0)
			if (ById('pbraidtab')) ById('pbraidtab').value = ''+culang.raidStopRaids+' ('+ t.activecount + ')'
			else if (t.resuming == false && t.stopping == false && t.deleting == false)
				if (ById('pbraidtab')) ById('pbraidtab').value = ''+culang.raidStopRaids+' ('+ t.activecount + ')'
		if (t.resuming == false && t.resuming == false && t.deleting == false && t.stopcount !=0)
			if (ById('pbraidtabRes')) ById('pbraidtabRes').value = ''+culang.raidResumeRaids+' ('+ t.stopcount + ')'
			else if (t.resuming == false && t.stopping == false && t.deleting == false)
				if (ById('pbraidtabRes')) ById('pbraidtabRes').value = ''+culang.raidResumeRaids+' ('+ t.stopcount + ')'
		if (t.resuming == false && t.stopping == false && t.deleting == false && t.stopcount !=0)
			if (ById('pbraidtabDel')) ById('pbraidtabDel').value = ''+culang.raidDeleteRaids+' ('+ t.stopcount + ')'
			else if (t.resuming == false && t.stopping == false && t.deleting == false)
				if (ById('pbraidtabDel')) ById('pbraidtabDel').value = ''+culang.raidDeleteRaids+' ('+ t.stopcount + ')'
	},

	paint : function ()	{
		var t = Tabs.Raid;

		var botMarchStat = {0:'Inactive',
			1:'Raiding',
			2:'Returning',
			3:'Stopped',
			4:'Resting',
			5:'Unknown',
			7:'Situation Changed',
			8:'Returning',
			9:'Aborting'};
		var botStat = {0:'Undefined',
			1:'Marching',
			2:'Returning',
			3:'Stopped',
			4:'Insufficient Troops',
			5:'Max Raids Exceeded',
			7:'Timed out',
			8:'Resting'};


		var o = '';
		if (t.rslt.settings != undefined) o+= '<B>'+culang.raidTimer+' <span class="boldRed">'+ timestr( 86400 - ( unixTime() - t.rslt.settings.lastUpdated )) +'</span></b>';
		ById('ptRaidTimer').innerHTML = o;

		var z ='<TABLE class=pdxTab><TR><TD width=60px align=center><A onclick="pbStopAll('+t.cityId+')">'+culang.raidStop+'</a></td><TD width=70px><u><b>'+culang.mainTime+'</b></u></td><TD width=85px><u><b>'+culang.shortCoordinate+'</b></u></td><TD width=50px><u><b>'+uW.g_js_strings.commonstr.level+'</b></u></td><TD width=50px></td><TD width=50px>&nbsp;</td></TR>';
		if (t.rslt['queue'] != ""){
			for (y in t.rslt['queue']) {
				if (t.rslt['queue'][y]['botMarches'] != undefined) {
					for (k in Seed.queue_atkp['city' + t.cityId]){
						if (Seed.queue_atkp['city' + t.cityId][k]['marchId'] == t.rslt['queue'][y]['botMarches']['marchId']) {
							botMarchStatus = Seed.queue_atkp['city' + t.cityId][k]['botMarchStatus'];
							MarchStatus = Seed.queue_atkp['city' + t.cityId][k]['marchStatus'];
							restPeriod = (Seed.queue_atkp['city' + t.cityId][k]['restPeriod']/60);
							destinationUnixTime = Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'];
							returnUnixTime = Seed.queue_atkp['city' + t.cityId][k]['returnUnixTime']
							now = unixTime();
							z+='<TR>';
							if (MarchStatus == 1) z+='<TD align=center><img src="'+IMGmarchAttacking+'"></td>';
							if (MarchStatus == 8 && (destinationUnixTime - now) <= 0 && botMarchStatus !=3 && returnUnixTime > now) z+='<TD align=center><img src="'+IMGmarchReturning+'"></td>';
							if (MarchStatus == 3) z+='<TD align=center><img src="'+IMGmarchRaidStoppedDesat+'"></td>';
							if (MarchStatus == 4 || (returnUnixTime < now  && botMarchStatus !=3)) z+='<TD align=center><img src="'+IMGmarchRaidReset+'"></td>';

							if (destinationUnixTime >= now) z+='<TD>'+ timestr(Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'] - unixTime())+'</td>';
							if (destinationUnixTime <= now) {
								if ((destinationUnixTime - now) <= 0 && returnUnixTime > now) z+='<TD>'+ timestr(returnUnixTime - now)+'</td>';
								if (returnUnixTime <= now) z+='<TD>'+ timestr(now - returnUnixTime)+'</td>';
							}
						}
					}
					z+="<TD><a href='javascript:void(0)' onclick='clickKoords(event)' class='coordinateLink'>("+ t.rslt['queue'][y]['botMarches']['toXCoord'] +","+ t.rslt['queue'][y]['botMarches']['toYCoord']+")</a></td>";
					z+='<TD align=center>'+ t.rslt['queue'][y]['botMarches']['toTileLevel'] +'</td>';
					if (botMarchStatus == 3) z+='<TD><A onclick="pbEditRaid('+ y +')">'+culang.buttonEdit+'</a></td>';
					else z+='<TD><FONT COLOR= "CCCCCC">'+culang.buttonEdit+'</font></td>';
					if (botMarchStatus == 3) z+='<TD align=center><A onclick="pbDeleteRaid('+ t.rslt['queue'][y]['botMarches']['marchId']+')">'+culang.mainDelete+'</a></td>';
					else z+='<TD align=center><FONT COLOR= "CCCCCC">'+culang.mainDelete+'</font></td>';
					z +='<TD width=25px></td><TD>'+culang.raidRestPeriod+' '+ timestr(restPeriod) +'</td>';
					z+='</tr>';
				}
			}
		}
		z+='</table>';
		if (t.rslt['queue'] == "") z ='<TABLE class=pdxTab ><TR><TD align=center><i><b>'+culang.raidNoFound+'</b></i></td></TR>';
		ById('PaintRaids').innerHTML = z;

		var check = true;
		if (t.save != ""){
			var a ='<TABLE class=pdxTab><TR><TD width=60px></td><TD width=70px></td><TD width=85px>'+culang.shortCoordinate+'</td><TD width=50px>'+uW.g_js_strings.commonstr.level+'</td><TD width=50px></td><TD width=50px></td></tr>';
			for (y in t.save){
				if (t.save[y] != undefined && t.cityId == t.save[y]['cityId']){
					a +='<TR><TD align=center><A onclick="pbDeleteSavedRaid('+ t.save[y]['marchId'] +')"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.raidDeleteNote+'"></a></td>';
					a +="<TD></td><TD><FONT COLOR='#CC0000'><a href='javascript:void(0)' onclick='clickKoords(event)' class='coordinateLink'>("+t.save[y]['toXCoord']+","+t.save[y]['toYCoord']+")</a></font></td>";
					a +='<TD align=center>'+t.save[y]['toTileLevel']+'</td>';
					a +='<TD><A onclick="pbEditSavedRaid('+ y +')">'+culang.buttonEdit+'</a></td>';
					a +='<TD align=center><A onclick="pbAddRaid('+ t.save[y]['marchId']+')">'+culang.buttonAdd+'</a></td></tr>';
					check = false;
				}
			}
			m+='</table>';
		}

		if (check) a ='<TABLE class=pdxTab><TR><TD align=center><i>'+culang.raidSaveNoFound+'</i></td></TR>';

		ById('SavedRaids').innerHTML = a;

		uW.pbDeleteRaid = t.DeleteRaid;
		uW.pbEditRaid = t.EditRaid;
		uW.pbAddRaid = t.AddRaid;
		uW.pbDeleteSavedRaid = t.DeleteSavedRaid;
		uW.pbEditSavedRaid = t.EditSavedRaid;
		uW.pbStopAll = t.StopCityRaids;
	},

	DeleteSavedRaid : function (Id){
		var t = Tabs.Raid;
		for (yy=0;yy<t.save.length;yy++){
			if (t.save[yy]['marchId'] == Id){
				t.save.splice (yy,1);
			}
		}
		var serverID = getServerId();
		setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
		t.paint();
	},

	EditSavedRaid : function (y){
		var t = Tabs.Raid;
		var pop = new CPopup ('pbEditRaid', 0,0, 750,350, true);
		if (t.popFirst){
			pop.centerMe (mainPop.getMainDiv());
			t.popFirst = false;
		}
		pop.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.raidEditHead+'</div>';
		cityId =  t.save[y]['cityId'];

		var m = '<BR><TABLE id=pbRaidAdd height=0% class=pdxTab><TR align="center">';
		m+='<TR></tr><TR><TD width=25px>X= <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.save[y]['toXCoord']+'></td>';
		m+='<TD width=10px></td><TD widht=25px>Y= <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.save[y]['toYCoord'] +'></td>';
		m+='<TD width=25px></td><TD>'+culang.mainRound+': '+ timestr((t.save[y]['returnUnixTime'] - t.save[y]['destinationUnixTime'])*2)+ '</td></tr></table>';

		m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pdxTab><TR align="center">';
		m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyTroop+'"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt1']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleMilitiaman+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt2']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleScout+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt3']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddlePikeman+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt4']) +'</td></tr>'
		m += '<TR><TD><INPUT id=Unit1 type=text size=6 maxlength=6 value="'+ t.save[y]['unit1Count']+'"></td>';
		m += '<TD><INPUT id=Unit2 type=text size=6 maxlength=6 value="'+ t.save[y]['unit2Count']+'"></td>';
		m += '<TD><INPUT id=Unit3 type=text size=6 maxlength=6 value="'+ t.save[y]['unit3Count']+'"></td>';
		m += '<TD><INPUT id=Unit4 type=text size=6 maxlength=6 value="'+ t.save[y]['unit4Count']+'"></td></tr>';

		m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSwordsman+'"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt5']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleArcher+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt6']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleCavalry+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt7']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleHeavyCavalry+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt8']) +'</td></tr>'
		m += '<TR><TD><INPUT id=Unit5 type=text size=6 maxlength=6 value="'+ t.save[y]['unit5Count']+'"></td>';
		m += '<TD><INPUT id=Unit6 type=text size=6 maxlength=6 value="'+ t.save[y]['unit6Count']+'"></td>';
		m += '<TD><INPUT id=Unit7 type=text size=6 maxlength=6 value="'+ t.save[y]['unit7Count']+'"></td>';
		m += '<TD><INPUT id=Unit8 type=text size=6 maxlength=6 value="'+ t.save[y]['unit8Count']+'"></td></tr>';

		m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyWagon+'"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt9']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleBallista+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt10']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleBatteringRam+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt11']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleCatapult+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt12']) +'</td></tr>'
		m += '<TR><TD><INPUT id=Unit9 type=text size=6 maxlength=6 value="'+ t.save[y]['unit9Count']+'"></td>';
		m += '<TD><INPUT id=Unit10 type=text size=6 maxlength=6 value="'+ t.save[y]['unit10Count']+'"></td>';
		m += '<TD><INPUT id=Unit11 type=text size=6 maxlength=6 value="'+ t.save[y]['unit11Count']+'"></td>';
		m += '<TD><INPUT id=Unit12 type=text size=6 maxlength=6 value="'+ t.save[y]['unit12Count']+'"></td></tr>';
		
		m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_13_30.jpg"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt13']) +'</td>'
		m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_14_30.jpg"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt14']) +'</td>'
		m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_15_30.jpg"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt15']) +'</td>'
		m += '<TD rowspan="2"></td>'
		m += '<TD></tr>'
		m += '<TR><TD><INPUT id=Unit13 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit13Count']+'"></td>';
		m += '<TD><INPUT id=Unit14 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit14Count']+'"></td>';
		m += '<TD><INPUT id=Unit15 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit15Count']+'"></td>';
		m += '<TD></td></tr>';
		
		m += '</table>';

		m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
		m+= '<BR><CENTER>'+ strButton20(''+culang.buttonSave+'', 'id=pbSaveRaid') +'</center>';

		pop.getMainDiv().innerHTML = m;

		t.getKnights(cityId);

		document.getElementById ('AddKnights').value =  t.save[y]['knightId'];
		document.getElementById ('pbSaveRaid').addEventListener ('click', function(){
			t.save[y]['knightId'] = parseInt(document.getElementById ('AddKnights').value);
			t.save[y]['toXCoord'] = parseInt(document.getElementById ('toXCoord').value);
			t.save[y]['toYCoord'] = parseInt(document.getElementById ('toYCoord').value);
			t.save[y]['unit1Count'] = parseInt(document.getElementById ('Unit1').value);
			t.save[y]['unit2Count'] = parseInt(document.getElementById ('Unit2').value);
			t.save[y]['unit3Count'] = parseInt(document.getElementById ('Unit3').value);
			t.save[y]['unit4Count'] = parseInt(document.getElementById ('Unit4').value);
			t.save[y]['unit5Count'] = parseInt(document.getElementById ('Unit5').value);
			t.save[y]['unit6Count'] = parseInt(document.getElementById ('Unit6').value);
			t.save[y]['unit7Count'] = parseInt(document.getElementById ('Unit7').value);
			t.save[y]['unit8Count'] = parseInt(document.getElementById ('Unit8').value);
			t.save[y]['unit9Count'] = parseInt(document.getElementById ('Unit9').value);
			t.save[y]['unit10Count'] = parseInt(document.getElementById ('Unit10').value);
			t.save[y]['unit11Count'] = parseInt(document.getElementById ('Unit11').value);
			t.save[y]['unit12Count'] = parseInt(document.getElementById ('Unit12').value);
			t.save[y]['unit13Count'] = parseInt(document.getElementById ('Unit13').value);
			t.save[y]['unit14Count'] = parseInt(document.getElementById ('Unit14').value);
			t.save[y]['unit15Count'] = parseInt(document.getElementById ('Unit15').value);
			var serverID = getServerId();
			setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
			pop.show (false);
		}, false);

		pop.show (true);
	},

	EditRaid : function (y){
		var t = Tabs.Raid;
		var pop = new CPopup ('pbEditRaid', 0,0, 750,350, true);
		if (t.popFirst){
			pop.centerMe (mainPop.getMainDiv());
			t.popFirst = false;
		}
		pop.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.raidEditHead+'</div>';
		cityId = t.rslt['queue'][y]['botMarches']['cityId'];

		var m = '<BR><TABLE id=pbRaidAdd height=0% class=pdxTab><TR align="center">';
		m+='<TR></tr><TR><TD width=25px>X = <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.rslt['queue'][y]['botMarches']['toXCoord']+'></td>';
		m+='<TD width=10px></td><TD widht=25px>Y = <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.rslt['queue'][y]['botMarches']['toYCoord'] +'></td>';
		m+='<TD width=25px></td><TD>'+culang.mainRound+': '+ timestr((t.rslt['queue'][y]['botMarches']['returnUnixTime'] - t.rslt['queue'][y]['botMarches']['destinationUnixTime'])*2)+ '</td></tr></table>';

		m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pdxTab><TR align="center">';
		m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyTroop+'"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt1']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleMilitiaman+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt2']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleScout+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt3']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddlePikeman+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt4']) +'</td></tr>'
		m += '<TR><TD><INPUT id=Unit1 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit1Count']+'"></td>';
		m += '<TD><INPUT id=Unit2 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit2Count']+'"></td>';
		m += '<TD><INPUT id=Unit3 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit3Count']+'"></td>';
		m += '<TD><INPUT id=Unit4 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit4Count']+'"></td></tr>';

		m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSwordsman+'"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt5']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleArcher+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt6']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleCavalry+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt7']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleHeavyCavalry+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt8']) +'</td></tr>'
		m += '<TR><TD><INPUT id=Unit5 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit5Count']+'"></td>';
		m += '<TD><INPUT id=Unit6 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit6Count']+'"></td>';
		m += '<TD><INPUT id=Unit7 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit7Count']+'"></td>';
		m += '<TD><INPUT id=Unit8 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit8Count']+'"></td></tr>';

		m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyWagon+'"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt9']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleBallista+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt10']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleBatteringRam+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt11']) +'</td>'
		m += '<TD rowspan="2"><img src="'+IMGmiddleCatapult+'"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt12']) +'</td></tr>'
		m += '<TR><TD><INPUT id=Unit9 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit9Count']+'"></td>';
		m += '<TD><INPUT id=Unit10 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit10Count']+'"></td>';
		m += '<TD><INPUT id=Unit11 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit11Count']+'"></td>';
		m += '<TD><INPUT id=Unit12 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit12Count']+'"></td></tr>';
		
		m += '<TR><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_13_30.jpg"></td>';
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt13']) +'</td>'
		m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_14_30.jpg"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt14']) +'</td>'
		m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_15_30.jpg"></td>'
		m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt15']) +'</td>'
		m += '<TD rowspan="2"></td>'
		m += '<TD></tr>'
		m += '<TR><TD><INPUT id=Unit13 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit13Count']+'"></td>';
		m += '<TD><INPUT id=Unit14 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit14Count']+'"></td>';
		m += '<TD><INPUT id=Unit15 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit15Count']+'"></td>';
		m += '<TD></td></tr>';
		
		m += '</table>';

		m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
		m+= '<BR><CENTER>'+ strButton20('Save', 'id=pbRaidSave') +'</center>';

		pop.getMainDiv().innerHTML = m;

		t.getKnights(cityId);

		document.getElementById ('AddKnights').value =  t.rslt['queue'][y]['botMarches']['knightId'];
		document.getElementById ('pbRaidSave').addEventListener ('click', function(){
			var params = uW.Object.clone(uW.g_ajaxparams);

			params.pf = 0;
			params.ctrl = 'BotManager';
			params.action = 'editMarch';
			params.settings = {};
			params.settings.cityId = t.rslt['queue'][y]['botMarches']['fromCityId'];
			params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};
			params.queue[0].cityMarches.knightId = parseInt(document.getElementById ('AddKnights').value);
			params.queue[0].cityMarches.toXCoord =  parseInt(document.getElementById ('toXCoord').value);
			params.queue[0].cityMarches.toYCoord =  parseInt(document.getElementById ('toYCoord').value);
			params.queue[0].cityMarches.unit0Count = 0; //document.getElementById ('Unit0').value;
			params.queue[0].cityMarches.unit1Count =  parseInt(document.getElementById ('Unit1').value);
			params.queue[0].cityMarches.unit2Count = parseInt(document.getElementById ('Unit2').value);
			params.queue[0].cityMarches.unit3Count = parseInt(document.getElementById ('Unit3').value);
			params.queue[0].cityMarches.unit4Count = parseInt(document.getElementById ('Unit4').value);
			params.queue[0].cityMarches.unit5Count = parseInt(document.getElementById ('Unit5').value);
			params.queue[0].cityMarches.unit6Count = parseInt(document.getElementById ('Unit6').value);
			params.queue[0].cityMarches.unit7Count = parseInt(document.getElementById ('Unit7').value);
			params.queue[0].cityMarches.unit8Count = parseInt(document.getElementById ('Unit8').value);
			params.queue[0].cityMarches.unit9Count = parseInt(document.getElementById ('Unit9').value);
			params.queue[0].cityMarches.unit10Count = parseInt(document.getElementById ('Unit10').value);
			params.queue[0].cityMarches.unit11Count = parseInt(document.getElementById ('Unit11').value);
			params.queue[0].cityMarches.unit12Count = parseInt(document.getElementById ('Unit12').value);
			params.queue[0].cityMarches.unit13Count = parseInt(document.getElementById ('Unit13').value);
			params.queue[0].cityMarches.unit14Count = parseInt(document.getElementById ('Unit14').value);
			params.queue[0].cityMarches.unit15Count = parseInt(document.getElementById ('Unit15').value);
			params.queue[0].cityMarches.marchId =  t.rslt['queue'][y]['botMarches']['marchId'];

			new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				loading: true,
				onSuccess: function(transport){
					var rslt = eval("(" + transport.responseText + ")");
					if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
					if (rslt.ok) {
						pop.show (false);
						uW.cityinfo_army();
						setTimeout(uW.update_seed_ajax, 250);
						setTimeout(t.GetRaids, (750),Seed.cities[i][0]);
					}
				},
			});
		}, false);

		pop.show (true);
	},

	DeleteRaid : function (Id){
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);

		for (y in t.rslt['queue']) {
			if (t.rslt['queue'][y]['botMarches'] != undefined) {
				if (t.rslt['queue'][y]['botMarches']['marchId'] == Id) {
					marchId = t.rslt['queue'][y]['botMarches']['marchId'];
					cityId = t.rslt['queue'][y]['botMarches']['cityId'];
					knightId = t.rslt['queue'][y]['botMarches']['knightId'];
					toTileLevel = t.rslt['queue'][y]['botMarches']['toTileLevel'];
					returnUnixTime = t.rslt['queue'][y]['botMarches']['returnUnixTime'];
					destinationUnixTime = t.rslt['queue'][y]['botMarches']['destinationUnixTime'];
					toXCoord = t.rslt['queue'][y]['botMarches']['toXCoord'];
					toYCoord = t.rslt['queue'][y]['botMarches']['toYCoord'];
					var units = {};
					for (i=1;i<16;i++) units[i] = t.rslt['queue'][y]['botMarches']['unit'+i+'Count'];
				}
			}
		}

		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'deleteMarch';
		params.marchId = marchId;
		params.settings = {};
		params.settings.cityId = cityId;

		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					var serverID = getServerId();
					t.save = GM_getValue ('SavedRaids_'+serverID);
					if (t.save == undefined) t.save =new Array();
					else t.save = JSON2.parse (t.save);

					t.save.push ({
						marchId:		marchId,
						cityId:   		cityId,
						knightId:		knightId,
						toTileLevel:	toTileLevel,
						returnUnixTime:	destinationUnixTime,
						returnUnixTime:	returnUnixTime,
						toXCoord:		toXCoord,
						toYCoord:		toYCoord,
						unit1Count: 	units[1],
						unit2Count: 	units[2],
						unit3Count: 	units[3],
						unit4Count: 	units[4],
						unit5Count: 	units[5],
						unit6Count: 	units[6],
						unit7Count: 	units[7],
						unit8Count: 	units[8],
						unit9Count: 	units[9],
						unit10Count: 	units[10],
						unit11Count: 	units[11],
						unit12Count: 	units[12],
						unit13Count: 	units[13],
						unit14Count: 	units[14],
						unit15Count: 	units[15],
					});
					var troops = Seed.units["city" + cityId];
					for (var u = 1; u <= 15; ++u) {
						var troop_number = parseInt(rslt["unit" + u + "Return"]);
						if (isNaN(troop_number)) {
							troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
						} else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
						troops["unt" + u] = troop_number;
					}
					for (u in Seed.queue_atkp['city' + cityId]){
						if (Seed.queue_atkp['city' + cityId][u]['marchId'] == marchId){
							Seed.queue_atkp['city' + cityId][u] = "";
							uW.seed.queue_atkp['city' + cityId] = Seed.queue_atkp['city' + cityId];
						}
					}

					for (u in Seed.knights['city' + cityId]){
						if (Seed.knights['city' + cityId][u]['knightId'] == knightId){
							Seed.knights['city' + cityId][u]["knightStatus"] = 1;
							uW.seed.knights['city' + cityId] = Seed.knights['city' + cityId];
						}
					}

					GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));
					t.save = null;
					uW.cityinfo_army();
					setTimeout(uW.update_seed_ajax, 250);
					t.GetRaids(cityId);
				}
			},
		});
	},

	StopCityRaids : function (cityId){
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);

		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'stopAll';
		params.settings = {};
		params.settings.cityId = cityId;

		new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {

				}
			},
		});
		setTimeout(t.GetRaids, (750), cityId);
	},

	StopAllRaids : function (){
		var t = Tabs.Raid;
		if (t.stopping == true || t.resuming == true || t.deleting == true) return;
		if (t.activecount == 0) return;
		t.stopping = true;
		for (i=0;i<Seed.cities.length;i++){
			setTimeout(t.DoAllStop, (i*1500),i);
		}
	},

	ResumeAllRaids : function (){
		var t = Tabs.Raid;
		if (t.stopping == true || t.resuming == true || t.deleting == true) return;
		if (t.stopcount == 0) return;
		t.resuming = true;
		for (i=0;i<Seed.cities.length;i++){
			setTimeout(t.DoAllResume, (i*1500),i);
		}
	},


	DeleteAllRaids : function (){
		var t = Tabs.Raid;
		if (t.stopping == true || t.resuming == true || t.deleting == true) return;
		if (t.stopcount == 0) return;
		t.deleting = true;
		count=0;
		t.count = t.stopcount;
		for (d=0; d< Seed.cities.length;d++) {
			cityID = 'city' + Seed.cities[d][0];
			for (e in Seed.queue_atkp[cityID]){
				destinationUnixTime = Seed.queue_atkp[cityID][e]['destinationUnixTime'];
				MarchStatus = Seed.queue_atkp[cityID][e]['marchStatus'];
				MarchType = Seed.queue_atkp[cityID][e]['marchType'];
				if (MarchType == 9 && (botMarchStatus == 3 || MarchStatus == 3)) {
					count++;
					setTimeout(t.DoAllDelete, (count*1250), (Seed.queue_atkp[cityID][e]['marchId']),d,count);
				}
			}
		}
	},


	DoAllStop: function(i) {
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'stopAll';
		params.settings = {};
		params.settings.cityId = Seed.cities[i][0];

		new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					t.stopprogress = t.stopprogress + (100/Seed.cities.length);

					if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopping+': '+ t.stopprogress.toFixed(0) + '%';
					if (t.stopprogress.toFixed(0) == 100) {
						t.stopprogress = 0;
						setTimeout(
							function(){
								if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopRaids+' ('+ t.activecount + ')';
								t.stopping = false;

							}, (5000));

					}
				}
				else {
					if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllStop, (2000),i);
					else {
						t.stopprogress = t.stopprogress + (100/Seed.cities.length);
						if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopping+': '+ t.stopprogress.toFixed(0) + '%';

						if (t.stopprogress.toFixed(0) == 100) {
							t.stopprogress = 0;
							setTimeout(function(){
								if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopRaids+' ('+ t.activecount + ')';
								t.stopping = false;
							}, (5000));

						}
					}
				}
			},
		});
	},

	DoAllResume: function(i) {
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'resumeAll';
		params.settings = {};
		params.settings.cityId = Seed.cities[i][0];

		new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					t.stopprogress = t.stopprogress + (100/Seed.cities.length);
					if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResuming+': '+ t.stopprogress.toFixed(0) + '%';
					if (t.stopprogress.toFixed(0) == 100) {
						t.stopprogress = 0;
						setTimeout(function(){

							if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResumeRaids+' ('+ t.stopcount + ')';

							t.resuming = false;
						}, (5000));
					}
				} else {
					if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllResume, (2000),i);
					else {
						t.stopprogress = t.stopprogress + (100/Seed.cities.length);
						if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResuming+': '+ t.stopprogress.toFixed(0) + '%';
						if (t.stopprogress.toFixed(0) == 100) {
							t.stopprogress = 0;
							setTimeout(function(){
								if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResumeRaids+' ('+ t.stopcount + ')';
								t.resuming = false;}, (5000));
						}
					}
				}
			},
		});
	},

	DoAllDelete : function (Id,city,count){
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);
		cityID = 'city'+ Seed.cities[city][0];
		for (f in Seed.queue_atkp[cityID]){
			if (Seed.queue_atkp[cityID][f]['marchId'] == Id) {
				marchId = Seed.queue_atkp[cityID][f]['marchId'];
				cityId = Seed.queue_atkp[cityID][f]['cityId'];
				knightId = Seed.queue_atkp[cityID][f]['knightId'];
				toTileLevel = Seed.queue_atkp[cityID][f]['toTileLevel'];
				returnUnixTime = Seed.queue_atkp[cityID][f]['returnUnixTime'];
				destinationUnixTime = Seed.queue_atkp[cityID][f]['destinationUnixTime'];
				toXCoord = Seed.queue_atkp[cityID][f]['toXCoord'];
				toYCoord = Seed.queue_atkp[cityID][f]['toYCoord'];
				var units = {};
				for (i=1;i<16;i++) units[i] = Seed.queue_atkp[cityID][f]['unit'+i+'Count'];
			}
		}

		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'deleteMarch';
		params.marchId = marchId;
		params.settings = {};
		params.settings.cityId = cityId;

		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt != "") {
					var serverID = getServerId();
					t.save = GM_getValue ('SavedRaids_'+serverID, "[]");
					if (t.save != undefined) t.save = JSON2.parse (t.save);
					if (t.save == undefined) t.save =new Array();

					t.save.push ({
						marchId:		marchId,
						cityId:   		cityId,
						knightId:		knightId,
						toTileLevel:	toTileLevel,
						returnUnixTime:	destinationUnixTime,
						returnUnixTime:	returnUnixTime,
						toXCoord:		toXCoord,
						toYCoord:		toYCoord,
						unit1Count: 	units[1],
						unit2Count: 	units[2],
						unit3Count: 	units[3],
						unit4Count: 	units[4],
						unit5Count: 	units[5],
						unit6Count: 	units[6],
						unit7Count: 	units[7],
						unit8Count: 	units[8],
						unit9Count: 	units[9],
						unit10Count: 	units[10],
						unit11Count: 	units[11],
						unit12Count: 	units[12],
						unit13Count: 	units[13],
						unit14Count: 	units[14],
						unit15Count: 	units[15],
					});

					var troops = Seed.units["city" + cityId];
					for (var u = 1; u <= 15; ++u) {
						var troop_number = parseInt(rslt["unit" + u + "Return"]);
						if (isNaN(troop_number)) {
							troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
						} else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
						troops["unt" + u] = troop_number;
					}

					setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
					uW.cityinfo_army();
					setTimeout(uW.update_seed_ajax, 250);
				}
			},
		});
		t.stopprogress = count * (100/t.count);
		if (ById("pbraidtabRes")) ById("pbraidtabDel").value=''+culang.raidDeleting+' '+ t.stopprogress.toFixed(0) + '%';
		if (t.stopprogress.toFixed(0) == 100) {
			t.stopprogress = 0;
			t.GetRaids(cityId);
		}

	},
	AddRaid : function (Id){
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);
		update = {};

		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'saveMarch';
		params.settings = {};
		params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};

		for (y in t.save){
			if (t.save[y]['marchId'] == Id){
				params.settings.cityId = t.save[y]['cityId'];
				params.queue[0].cityMarches.knightId = t.save[y]['knightId'];
				params.queue[0].cityMarches.toXCoord = t.save[y]['toXCoord'];
				params.queue[0].cityMarches.toYCoord = t.save[y]['toYCoord'];
				params.queue[0].cityMarches.unit0Count = 0;
				params.queue[0].cityMarches.unit1Count = t.save[y]['unit1Count'];
				params.queue[0].cityMarches.unit2Count = t.save[y]['unit2Count'];
				params.queue[0].cityMarches.unit3Count = t.save[y]['unit3Count'];
				params.queue[0].cityMarches.unit4Count = t.save[y]['unit4Count'];
				params.queue[0].cityMarches.unit5Count = t.save[y]['unit5Count'];
				params.queue[0].cityMarches.unit6Count = t.save[y]['unit6Count'];
				params.queue[0].cityMarches.unit7Count = t.save[y]['unit7Count'];
				params.queue[0].cityMarches.unit8Count = t.save[y]['unit8Count'];
				params.queue[0].cityMarches.unit9Count = t.save[y]['unit9Count'];
				params.queue[0].cityMarches.unit10Count = t.save[y]['unit10Count'];
				params.queue[0].cityMarches.unit11Count = t.save[y]['unit12Count'];
				params.queue[0].cityMarches.unit12Count = t.save[y]['unit12Count'];
				params.queue[0].cityMarches.unit13Count = t.save[y]['unit13Count'];
				params.queue[0].cityMarches.unit14Count = t.save[y]['unit14Count'];
				params.queue[0].cityMarches.unit15Count = t.save[y]['unit15Count'];
			}
		}

		new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					t.GetRaids(params.settings.cityId);
					uW.cityinfo_army();
					setTimeout(uW.update_seed_ajax, 250);
					for (yy=0;yy<t.save.length;yy++){
						if (t.save[yy]['marchId'] == Id){
							t.save.splice (yy,1);
						}
					}
					var serverID = getServerId();
					setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
					t.paint();
				} else {
					alert('Error: '+ rslt.msg);
				}
			},
		});
	},


	getKnights : function(cityId){
		var t = Tabs.Raid;
		var knt = new Array();
		var status ="";
		for (k in Seed.knights['city' + cityId]){
			if ( Seed.leaders['city' + cityId]["resourcefulnessKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["politicsKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["combatKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["intelligenceKnightId"] != Seed.knights['city' + cityId][k]["knightId"]){
				if (Seed.knights['city' + cityId][k]["knightStatus"] == 1 ) status = "Free";
				else status = "Marching";
				knt.push ({
					Name:   Seed.knights['city' + cityId][k]["knightName"],
					Combat:	parseInt(Seed.knights['city' + cityId][k]["combat"]),
					ID:		Seed.knights['city' + cityId][k]["knightId"],
					Status: status,
				});
			}
		}
		knt = knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
		ById('AddKnights').options.length=0;
		var o = document.createElement("option");
		o.text = '-- '+culang.mainSelect+' --';
		o.value = 0;
		ById("AddKnights").options.add(o);
		for (k in knt){
			if (knt[k]["Name"] !=undefined){
				var o = document.createElement("option");
				o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +') (' + knt[k]["Status"] +')');
				o.value = knt[k]["ID"];
				ById("AddKnights").options.add(o);
			}
		}
	},


	clickCitySelect : function (city){
		var t = Tabs.Raid;
		t.cityId = city['id'];
		t.GetRaids(t.cityId);
	},

	checkRaids : function (){
		var t = Tabs.Raid;
		var now = unixTime();
		if(!Options.RaidRunning) return;
		if ( (now - Options.RaidReset) > 7200 ) {
			Options.RaidReset = now;
			saveOptions();
			for (g=0;g<Seed.cities.length;g++){
				t.citiesdone = "";
				setTimeout(t.resetRaids, (1500*g), Seed.cities[g][0],Seed.cities[g][1]);
			}
		}
		t.raidtimer = setTimeout(t.checkRaids, 60*60*1000); // toute les heures !
	},

	GetRaids : function(cityId){
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);

		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'getMarches';
		params.settings = {};
		params.settings.cityId = cityId;


		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					t.rslt = rslt;
					t.paint();
					uW.cityinfo_army();
					setTimeout(uW.update_seed_ajax, 250);
				}
			},
		});
	},

	resetRaids : function(cityId,cityName){
		var t = Tabs.Raid;
		var params = uW.Object.clone(uW.g_ajaxparams);

		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'resetRaidTimer';
		params.settings = {};
		params.settings.cityId = cityId;


		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
					actionLog(""+culang.mainRaid+""," "+culang.logResetTimer+" <span class=boldGreen>"+cityName+"</span> "+culang.logResetTimer2+"");
					uW.cityinfo_army();
					setTimeout(uW.update_seed_ajax, 250);
					t.citiesdone += cityName + ' ';
				}
			},
		});
	},
	sendreport: function(){
		var t = Tabs.Raid;
		if(!Options.foodreport) return;
		var now = new Date().getTime()/1000.0;
		now = now.toFixed(0);
		if (now < (parseInt(Options.LastReport)+(Options.MsgInterval*60*60))) return;

		var total = 0;
		var message = ''+culang.raidReportStats+' %0A';
		message += '%0A '+culang.raidReportFoodGain+' '+ Options.MsgInterval +' '+culang.raidReportFoodGain2+' %0A';
		for (q=1;q<=Seed.cities.length;q++){
			var cityID = 'city' + Seed.cities[q-1][0];
			var gain = parseInt(Seed.resources[cityID]['rec1'][0] / 3600) - Options.Foodstatus[q];
			message+= ''+culang.mainCastle+': '+Seed.cities[q-1][1] + ' '+culang.raidReportFoodGainStat+' ' + addCommas(Options.Foodstatus[q]) + ' '+culang.raidReportFoodGainStat2+' ' + addCommas(parseInt(Seed.resources[cityID]['rec1'][0] / 3600)) + ' '+culang.raidReportFoodGainStat3+' ';
			message += addCommas(gain)  + '%0A';
			total += gain;
			Options.Foodstatus[q] = parseInt(Seed.resources[cityID]['rec1'][0] / 3600);
		}
		message += '%0A '+culang.raidReportFoodGainTotal+' '+addCommas(total)+'%0A';

		var params = uW.Object.clone(uW.g_ajaxparams);
		params.emailTo = Seed.player['name'];
		params.subject = ""+culang.raidReportOverview+"";
		params.message = message;
		params.requestType = "COMPOSED_MAIL";
		new AjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (message) {
				var rslt = eval("(" + message.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if (rslt.ok) {
				} else {
				}
			},
			onFailure: function () {
			},
		});

		Options.LastReport = now;
		saveOptions();
	},

	toggleRaidState : function (){
		var t = Tabs.Raid;
		if(Options.RaidRunning){
			Options.RaidRunning = false;
			t.raidtimer = null;
			ById('pbRaidStart').value = culang.raidAutoReset+' = '+culang.buttonOFF;
		} else {
			Options.RaidRunning = true;
			t.raidtimer = setTimeout(t.checkRaids, 5000);
			ById('pbRaidStart').value = culang.raidAutoReset+' = '+culang.buttonON;
		}
		saveOptions();
	},


	hide : function (){
		var t = Tabs.Raid;
		clearInterval(t.timerPaint);
		clearInterval(t.timerLookup);
	},

	show : function (){
		var t = Tabs.Raid;
		clearInterval(t.timerPaint);
		clearInterval(t.timerLookup);
		t.timerPaint = setInterval (t.paint,2000);
		t.timerLookup = setInterval(t.lookup, 3500);
	},
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/MultilangTabs.js">
//	
//	   KOC POWER - MULTITABS											        
//	
var wildNames={0:culang.kocBog,10:culang.kocGrassland,11:culang.kocLake,20:culang.kocForests,30:culang.kocHill,40:culang.kocMount,50:culang.kocPlain};var mercNames={0:culang.kocNoneHired,1:culang.kocNovices,2:culang.kocIntermediates,3:culang.kocVeterans}
function inspect(obj, maxLevels, level, doFunctions){
	var str = '', type, msg;
	if(level == null)  level = 0;
	if(maxLevels == null) maxLevels = 1;
	if(maxLevels < 1)
		return 'Inspect Error: Levels number must be > 0';
	if(obj == null)
		return 'ERROR: Object is NULL\n';
	var indent = '';
	for (var i=0; i<level; i++)
		indent += '  ';
	for(property in obj) {try {type =  matTypeof(obj[property]);if (doFunctions==true && (type == 'function')){str += indent + '(' + type + ') ' + property + "[FUNCTION]\n   " + ( (obj[property]==null)?(': null'):('')) +' = '+ obj[property] +"\n";} else if (type != 'function') {str += indent + '(' + type + ') ' + property + ( (obj[property]==null)?(': null'):('')) +' = '+ obj[property] +"\n";}
			if((type=='object' || type=='array') && (obj[property] != null) && (level+1 < maxLevels))
				str += inspect(obj[property], maxLevels, level+1, doFunctions);  // recurse
		}catch(err) {if(typeof(err) == 'string') msg = err;else if(err.message)        msg = err.message;else if(err.description)    msg = err.description;else msg = ''+culang.mainUnknown+'';str += '(Error) ' + property + ': ' + msg +"\n";}
	}
	str += "\n";return str;
}

eval(GM_getResourceText("SYSTEM_TABS"));
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/GlobalVar.js">
//	
//	   KOC POWER - GLOBAL VARS											        
//	


var knightRoles = [[culang.kocForeman, 'politics', culang.kocShortPolitics],[culang.kocMarschall, 'combat', culang.kocShortCombat],[culang.kocAlchemystic, 'intelligence', culang.kocShortIntelligence],[culang.kocSteward, 'resourcefulness', culang.kocShortRessource]];
var fortNamesShort = { 53:"" + culang.crossbows + "", 55:"" + culang.trebuchet + "", 60:"" + culang.trap + "", 61:"" + culang.caltr + "", 62:"" + culang.spiked + "", };
// VAR DASHBOARD
function createDashboard (){
	var Dashboard = document.createElement('div');
	var beacon = document.getElementById('mod_cityinfo');
	Dashboard.id='Dash_div_box';
	Dashboard.style.position = 'absolute';
	if (GlobalOptions.pbWideScreenStyle=="ultra") Dashboard.style.width= "450px";
	 else if (GlobalOptions.pbWideScreenStyle=="wide") Dashboard.style.width= "400px";
	  else Dashboard.style.width = Dashboard.style.width= "450px";
	if (!Options.pbChatOnRight) Dashboard.style.width= "450px";
  
	if (Options.dashboardX != 0) Dashboard.style.left = Options.dashboardX;
		else if (Options.pbChatOnRight) Dashboard.style.left = "1122px";
  	 else Dashboard.style.left = "760px";
	if (Options.dashboardY != 0) Dashboard.style.top = Options.dashboardY;
		else Dashboard.style.top = "110px"; 
  
	Dashboard.style.maxHeight = "1270px";
	Dashboard.style.boarder = "1px solid #FF0000;";
	Dashboard.style.zIndex = "99999";
	Dashboard.style['padding'] = "5px";
	Dashboard.style['MozBoxShadow'] = "1px 1px 3px #141516";
	Dashboard.style['WebkitBoxShadow'] = "1px 1px 3px #141516";
	Dashboard.style['boxShadow'] = "1px 1px 3px #141516";
  Dashboard.style.background = '#FFFFE6';
  Dashboard.style.overflow = 'auto';
	//beacon.parentNode.insertBefore(Dashboard, beacon);
	document.body.insertBefore (Dashboard, document.body.firstChild);
	ById('Dash_div_box').innerHTML = '<div id=Dash_head class=pdxStat>Dashboard</div><div id=Dash_div></div>';
	new CWinDrag (ById('Dash_div_box'),ById('Dash_div_box') , true);
	setInterval(function() {
		var db = ById('Dash_div_box');
		Options.dashboardX = db.style.left;
		Options.dashboardY = db.style.top;
	}, 1000);
}
var DashboardOptions = {
	foodLevel:10000000000,
    woodLevel:1000000000,
    stoneLevel:100000000,
    oreLevel:100000000,
    astoneLevel:250000,
    showRP:true,
    showMultiNote:true,
    showThrone:true,
    showStatus:true,
    showButtons:true,
    showReso:true,
    ShowResoCity:[true,true,true,true,true,true,true,true],
    ShowResoTypes:[null,true,true,true,true],
    showLog:true,
    showTroops:true,
    showTower:true,
    showWarnings:true,
    showMarches:true,
    showSacrifice:true,
}
var Dashboard = {
    tabOrder: 800,
    tabLabel: 'Dashboard',
    myDiv : null,
    Alerts: [],
    showMarchesInfo: true,
    
    init : function (div){
        var t = Dashboard;
        t.myDiv = div;
        Tabs.Reassign.readReassignState();
        Tabs.build.readBuildStates();

        createDashboard();
				
        if (GlobalOptions.pbWideScreenStyle=="wide" || GlobalOptions.pbWideScreenStyle=="ultra" || GlobalOptions.pbWideScreenStyle=="custom") {
			// var m = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashButtons\');">'+culang.mainButtons+'</a></div>';
			// m += '<DIV id="powerDashButtons" style="display:'+Options["powerDashButtons"]+';">';
			// m += '<BR><div id="kocPowerButtonsDashContainer"></div>';
			// m += '</div>'; // BUTTONS END
			var   m = '<DIV id=MultiDashNote></div><div id=dbHeader style="text-align:center;margin:0 auton;wdith: 100%"></div>';
			// m += '<TABLE class=pdxTab cellspacing=0 cellpadding=0>';
	        // m += '<TR><TD><INPUT id=AttackToggleD type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=CraftToggle type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=TransportToggle type=submit class=pbButton style="width: 120px;"></td></tr>';
	        // m += '<TR><TD><INPUT id=CrestToggleD type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=AutoDfToggle type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=AutotrainToggle type=submit class=pbButton style="width: 120px;"></td></tr>';
	        // m += '<TR><TD><INPUT id=AutoFarmToggle type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=ReassignToggle type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=AutoSalvageToggle type=submit class=pbButton style="width: 120px;"></td></tr>';        
	        // m += '<TR><TD>&nbsp</td></tr><TR><TD><INPUT id=BuildToggle type=submit class=pbButton style="width: 120px;"></td><TD><INPUT id=BuildModeToggle type=submit class=pbButton style="width: 120px;">&nbsp&nbsp<SPAN id=buildStatus style="vertical-align:bottom;"></span></td>';

	        m+='<DIV id=MarchesSendInfo></div>';
	        m += '<DIV id=CityStatus></div>';
	        // m += '<BR><div class="pdxStat">THRONE ROOM</div><DIV id=UpgradeStatus></div><DIV id=TriesStatus></div>';
	        m += '<DIV id=ShowTrPresets></div>';
	        m += '<DIV id=ShowRP></div>';
	        m += '<DIV id=SacrificePlaceholder></div>';
	        m += '<DIV id=TowerAlertPlaceholder></div>';
	        //m += '<BR><DIV id=ShowAutoTrain></div>';
	        m += '<DIV id=ShowTroops></div>';     
	        m += '<DIV id=AlertsPlaceholder></div>';
	        m += '<DIV id=ShowMarches></div>'; 
	        m += '<DIV id=ShowLog></div>';
        } else {
        	var m = '<div id=dbHeader></div>';
	        // m += '<TABLE width=100% class=pdxTab cellspacing=0 cellpadding=0>';
	        // m += '<TR><TD><INPUT id=AttackToggleD type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=CraftToggle type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=TransportToggle type=submit class=pbButton style="width: 120px;"></td></tr>';
	        // m += '<TR><TD><INPUT id=CrestToggleD type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=AutoDfToggle type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=AutotrainToggle type=submit class=pbButton style="width: 120px;"></td></tr>';
	        // m += '<TR><TD><INPUT id=AutoFarmToggle type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=ReassignToggle type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=AutoSalvageToggle type=submit class=pbButton style="width: 120px;"></td></tr>';        
	        // m += '<TR><TD>&nbsp</td></tr><TR><TD><INPUT id=BuildToggle type=submit class=pbButton style="width: 120px;"></td></tr><TR><TD><INPUT id=BuildModeToggle type=submit class=pbButton style="width: 120px;">&nbsp&nbsp<SPAN id=buildStatus style="vertical-align:bottom;"></span></td>';
	        // m += '</table>';
		m += '<div id="kocPowerButtonsDashContainer"></div>';
		m+='<BR><DIV id=MarchesSendInfo></div>';
		// m += '<BR><DIV id=ShowTrPresets></div>';
		m += '<DIV id=AlertsPlaceholder></div>'; 
        }
        ById('Dash_div').innerHTML = m;
		// if (ById('UpgradeStatus')) ById('UpgradeStatus').innerHTML = "<b>"+culang.throneStuffRepairItem+"</b> " + getThroneItemName(ThroneOptions.Items["0"]["id"]) + "<br/><b>"+culang.throneStuffRepairTimeLeft+"</b> <span class='boldRed'>" + timestr(diff)+ " <sup>("+ timestr(Seed.queue_throne.end - Seed.queue_throne.start) + ")</sup></span>";
		// if (ById('TriesStatus')) ById('TriesStatus').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;        uW.clearMarches = t.clearMarches;
		// if (ById('kocPowerButtonsDashContainer')) ById('kocPowerButtonsDashContainer').innerHTML = "";
		
 // BUTTONS
        // if (AtkOptions.Running) ATTACK BUTTON {document.getElementById('AttackToggleD').value = "Attack = ON";document.getElementById('AttackToggleD').setAttribute("class", "buttonDash_ON");}
        	// else {document.getElementById('AttackToggleD').value = "Attack = OFF";document.getElementById('AttackToggleD').setAttribute("class", "buttonDash_OFF");}
        // if (CraftOptions.Running) AUTO CRAFT BUTTON {document.getElementById('CraftToggle').value = "Crafting = ON";document.getElementById('CraftToggle').setAttribute("class", "buttonDash_ON");}
        	// else {document.getElementById('CraftToggle').value = "Crafting = OFF";document.getElementById('CraftToggle').setAttribute("class", "buttonDash_OFF");}
        // if (Tabs.Transport.traderState.running) {document.getElementById('TransportToggle').value = "Transport = ON";document.getElementById('TransportToggle').setAttribute("class", "buttonDash_ON");}
        	// else {document.getElementById('TransportToggle').value = "Transport = OFF"; document.getElementById('TransportToggle').setAttribute("class", "buttonDash_OFF");} 
        // if (CrestOptions.Running) {document.getElementById('CrestToggleD').value = "Crest = ON";document.getElementById('CrestToggleD').setAttribute("class", "buttonDash_ON");}
    		// else {document.getElementById('CrestToggleD').value = "Crest = OFF";document.getElementById('CrestToggleD').setAttribute("class", "buttonDash_OFF");}
    	// if (DFOptions.Running) {document.getElementById('AutoDfToggle').value = "Auto DF = ON";document.getElementById('AutoDfToggle').setAttribute("class", "buttonDash_ON");}
    		// else {document.getElementById('AutoDfToggle').value = "Auto DF = OFF";document.getElementById('AutoDfToggle').setAttribute("class", "buttonDash_OFF");}
		// if (TrainOptions.Running) {document.getElementById('AutotrainToggle').value = "AutoTrain = ON";document.getElementById('AutotrainToggle').setAttribute("class", "buttonDash_ON");}
			// else {document.getElementById('AutotrainToggle').value = "AutoTrain = OFF";document.getElementById('AutotrainToggle').setAttribute("class", "buttonDash_OFF");}
		// if (FarmOptions.Running) {document.getElementById('AutoFarmToggle').value = "Farming = ON";document.getElementById('AutoFarmToggle').setAttribute("class", "buttonDash_ON");}
			// else {document.getElementById('AutoFarmToggle').value = "Farming = OFF";document.getElementById('AutoFarmToggle').setAttribute("class", "buttonDash_OFF");}
		// if (Tabs.Reassign.reassignState.running) {document.getElementById('ReassignToggle').value = "Reassign = ON";document.getElementById('ReassignToggle').setAttribute("class", "buttonDash_ON");}
			// else {document.getElementById('ReassignToggle').value = "Reassign = OFF";document.getElementById('ReassignToggle').setAttribute("class", "buttonDash_OFF");}
		// if (Options.ThroneDeleteItems) {document.getElementById('AutoSalvageToggle').value = "Salvage = ON";document.getElementById('AutoSalvageToggle').setAttribute("class", "buttonDash_ON");}
			// else {document.getElementById('AutoSalvageToggle').value = "Salvage = OFF";document.getElementById('AutoSalvageToggle').setAttribute("class", "buttonDash_OFF");}
		// if (Tabs.build.buildStates.running=='ON') {document.getElementById('BuildToggle').value = "Auto Build = ON";document.getElementById('BuildToggle').setAttribute("class", "buttonDash_ON");}
		// if (Tabs.build.buildStates.running=='AUTO') {document.getElementById('BuildToggle').value = "Auto Build = AUTO";document.getElementById('BuildToggle').setAttribute("class", "buttonDash_ON");}		
		// if (Tabs.build.buildStates.running=='OFF') {document.getElementById('BuildToggle').value = "Auto Build = OFF";document.getElementById('BuildToggle').setAttribute("class", "buttonDash_OFF");}
		
		// document.getElementById('BuildModeToggle').value = "Build Mode = OFF";
		// document.getElementById('BuildModeToggle').setAttribute("class", "buttonDash_OFF");

		// document.getElementById('buildStatus').innerHTML = '<img src=""/>';	 



        // document.getElementById('AttackToggleD').addEventListener ('click', function(){Tabs.Attack.toggleAttackState();},false);
        // document.getElementById('CraftToggle').addEventListener ('click', function(){Tabs.AutoCraft.toggleStateRunning(this);},false); 
        // document.getElementById('TransportToggle').addEventListener ('click', function(){Tabs.Transport.toggleTraderState(this);},false);
        // document.getElementById('CrestToggleD').addEventListener ('click', function(){Tabs.Crest.toggleCrestState();},false);
        // document.getElementById('AutoDfToggle').addEventListener ('click', function(){Tabs.DF.toggleDFState(this);},false);  
        // document.getElementById('AutotrainToggle').addEventListener ('click', function(){Tabs.AutoTrain.toggleAutoTrainState(this);},false);
        // document.getElementById('AutoFarmToggle').addEventListener ('click', function(){Tabs.farm.toggleBarbState(this);},false);
        // document.getElementById('ReassignToggle').addEventListener ('click', function(){Tabs.Reassign.toggleReassignState(this);},false);
        // document.getElementById('AutoSalvageToggle').addEventListener ('click', function(){Tabs.Throne.ToggleSalvageState(this);},false);
        // document.getElementById('BuildToggle').addEventListener ('click', function(){Tabs.build.toggleStateRunning(this);},false);
        // document.getElementById('BuildModeToggle').addEventListener ('click', function(){Tabs.build.toggleStateMode(this);},false);
        
        if (GlobalOptions.pbWideScreenStyle=="wide" || GlobalOptions.pbWideScreenStyle=="ultra" || GlobalOptions.pbWideScreenStyle=="custom") {
        	if (DashboardOptions.showWarnings) t.CheckForAlerts();
	        // if (DashboardOptions.showThrone) t.ShowTrPresets();
	        t.RPM();
			if (DashboardOptions.showMultiNote) t.multiNote();
	        if (DashboardOptions.showStatus) t.CityStatus();
	        if (DashboardOptions.showTower) t.ShowTowerAlerts();
	        if (DashboardOptions.showLog) t.ShowLog();
	        if (DashboardOptions.showTroops) t.ShowTroops();
	        if (DashboardOptions.showSacrifice) t.showSacrifice();
	        t.ShowMarches();
	        //t.ShowAutoTrain();
        } else {
        	// if (DashboardOptions.showThrone) t.ShowTrPresetsMini();
	        t.RPM();
			// if (DashboardOptions.showStatus) t.CityStatus();
	        if (DashboardOptions.showWarnings) t.CheckForAlerts();
        }
    },

    CheckForAlerts: function (){
    	var t = Dashboard;
    	var foodLev = DashboardOptions.foodLevel
    	var woodLev = DashboardOptions.woodLevel
    	var stoneLev = DashboardOptions.stoneLevel
    	var oreLev = DashboardOptions.oreLevel
    	var astoneLev = DashboardOptions.astoneLevel
    	t.Alerts = [];
		for (var a=1; a<=5;a++) for(b=0; b<Cities.numCities; b++) {
			if (a==5) rec = Seed.resources["city" + Seed.cities[b][0]]['rec'+a][0];
				else rec = Math.round(Seed.resources["city" + Seed.cities[b][0]]['rec'+a][0]/3600);
    		switch (a){
    			case 1:if (rec < foodLev) t.Alerts.push(Seed.cities[b][1] + " (" + (b+1) +")"+culang.dashboard_alert_foodalert+" " + addCommas(rec));break;
    			case 2:	if (rec < woodLev) t.Alerts.push(Seed.cities[b][1] + " (" + (b+1) + ")"+culang.dashboard_alert_woodalert+" " + addCommas(rec));break;
    			case 3:	if (rec < stoneLev) t.Alerts.push(Seed.cities[b][1] + " (" + (b+1) + ")"+culang.dashboard_alert_stonealert+" " + addCommas(rec));break;
    			case 4:	if (rec < oreLev) t.Alerts.push(Seed.cities[b][1] + " (" + (b+1) + ")"+culang.dashboard_alert_orealert+" " + addCommas(rec));break;
    			case 5:	if (rec < astoneLev) t.Alerts.push(Seed.cities[b][1] + " (" + (b+1) + ")"+culang.dashboard_alert_aehteralert+" " + addCommas(rec));break;
    		}
    	}
    	for(b=0; b<Seed.cities.length; b++) if (Seed.queue_unt["city" + Seed.cities[b][0]].length == 0) t.Alerts.push(Seed.cities[b][1] +  " (" + (b+1) + ")"+culang.dashboard_alert_notroopstrain+"");

    	for(b=0; b<Seed.cities.length; b++) {
    		var check = false;
    		var tech = false;
    		var tech2 = false;
    		for (k in Seed.buildings["city" + Seed.cities[b][0]])	{
    			if (Seed.buildings["city" + Seed.cities[b][0]][k][1] < 9 && Seed.buildings["city" + Seed.cities[b][0]][k][2] < 500) 
						if (Seed.queue_con["city" + Seed.cities[b][0]].length == 0 && Tabs.build["bQ_" + Seed.cities[b][0]].length == 0) check = true;
    			if (Seed.buildings["city" + Seed.cities[b][0]][k][0] == 11 && Seed.queue_tch["city" + Seed.cities[b][0]].length == 0) {
						for (i=1; i<=17; i++) {
							if (i==7) continue;
							if (parseInt(Seed.tech['tch'+i]) < 12) tech = true;
						}
					}
    			if (Seed.buildings["city" + Seed.cities[b][0]][k][0] == 27 && Seed.queue_tch2["city" + Seed.cities[b][0]].length == 0) {
						for (i=1; i<=6; i++) {
							if (parseInt(Seed.tech2['tch'+i]) < 10) tech2 = true;
						}
					}
    		}
    		if (check) t.Alerts.push(Seed.cities[b][1] +  " (" + (b+1) + ")"+culang.dashboard_alert_nobuildqueue+"");
    		if (tech) t.Alerts.push(Seed.cities[b][1] +  " (" + (b+1) + ")"+culang.dashboard_alert_noreseach+"");
    		if (tech2) t.Alerts.push(Seed.cities[b][1] +  " (" + (b+1) + ")"+culang.dashboard_alert_nobritonreseach+"");
    	}
    	
    	var count = 0;
    	for (k in uW.kocThroneItems) count++;
    	if (count > (Seed.throne.rowNum*5)) t.Alerts.push(''+culang.dashboard_alert_thronefull+' (' + count + '/' + (Seed.throne.rowNum*5) +')');
    	
    	var msg="";
    	for (k=0;k<t.Alerts.length;k++) msg+= t.Alerts[k] + '<BR>';
    	if (t.Alerts.length > 0) {
    		document.getElementById('AlertsPlaceholder').innerHTML = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashWarings\');">'+culang.mainAlert+'</a></div><DIV id="powerDashWarings" style="display:'+Options["powerDashWarings"]+';"><DIV id=ShowAlerts></div></div>'; //style="height: 60px; overflow: auto"
    		document.getElementById('ShowAlerts').innerHTML = msg;	
    	} else document.getElementById('AlertsPlaceholder').innerHTML = "";
    },
   

    ShowMarches: function (){
    	var t = Dashboard;
    	var msg= "";
    	t.showMarchesInfo = true;
    	if (MarchOptions.Queue.length > 0) {
    		msg = '<BR><DIV class="pdxStat">'+culang.dashboard_marches_status+'&nbsp&nbsp<INPUT type=submit class=pbButton id=HideMarches value="'+culang.mainHide+'"></div><DIV id=MarchesInfo></div>';
    		document.getElementById('ShowMarches').innerHTML = msg;
    		msg = '<TABLE width=100% class=pdxTab>';
    		msg +='<TR><TD>'+culang.mainCastle+'</td><TD>'+culang.shortCoordinate+'</td><TD>'+culang.mainTarget+'</td><TD>'+culang.mainCity+'</td><TD>'+culang.mainTroops+'</td><TD>'+culang.mainAction+'</td>';
    		for (k=0;k<MarchOptions.Queue.length;k++) {
    			var action = MarchOptions.Queue[k];
    			for (postcity in Seed.cities) if (Seed.cities[postcity][0] == action.city) logcity = Seed.cities[postcity][1];
			    var total = 0;
				var info = "";
				var type="";
				for (i=1;i<=12;i++) total += parseInt(action[i]);
				switch (parseInt(action.tileType)) {
					case 0: info = "Bog";break;
					case 10: info = "Grassland";break;
					case 11: info = "Lake";break;
					case 20: info = "Woods";break;
					case 30: info = "Hills";break;
					case 40: info = "Mountain";break;
					case 50: info = "Plain";break;
					case 51: 
						if (action.targetCityName == null && !action.misted) info = "Barb Camp";
							else info = action.targetName;
						break;
					case 53: info = "Misted City";break;
				}
				switch (parseInt(action.action)) {
					case 1: type = "Transport";break;
					case 2: type = "Reinforce";break;
					case 3: type = "Scout";break;
					case 4: type = "Attack";break;
					case 5: type = "Reassign";break;
				} 
    			msg += '<TR><TD>'+logcity+'</td><TD><TD style="padding-right:10px;"><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ parseInt(action.targetX) +','+ parseInt(action.targetY) +')</a></td><TD>'+info+'</td><TD>'+action.targetCityName+'</td><TD>'+addCommas(total)+'</td><TD><INPUT type=submit class=pbButton id="dbDoAction' + k + '" value='+ type +' style="color:red;"></td>';
    		}
    		document.getElementById('MarchesInfo').innerHTML = msg;
			for (k=0;k<MarchOptions.Queue.length;k++) document.getElementById('dbDoAction' + k).addEventListener('click', function(){Tabs.March.doMarch(MarchOptions.Queue[this.id.substr(10)]);}, false);
			document.getElementById('HideMarches').addEventListener ('click', function(){t.clearMarches();},false);
		} else document.getElementById('ShowMarches').innerHTML = "";

	},

	showSacrifice: function(){
		var t = Dashboard;
		var now = unixTime();
		var NoSacrifice = true;
		for (var i=0;i<Seed.cities.length;i++) if (Seed.queue_sacr["city"+Seed.cities[i][0]][0]!=undefined) NoSacrifice = false;
    	if (NoSacrifice) {
    		document.getElementById('SacrificePlaceholder').innerHTML = "";
    		return;
    	}
		var msg = '<DIV class="pdxStat">'+culang.dashboard_sacifice_head+'</div><TABLE id=pbRPStats 50% class=pdxTab>';
		for (var i=0;i<Seed.cities.length;i++){
			var cityID = Seed.cities[i][0];
			if (Seed.queue_sacr["city"+cityID][0]!=undefined) msg+='<TR><TD width=150px>'+Seed.cities[i][1]+' (1)</td><TD width=30px><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+Seed.queue_sacr["city"+cityID][0].unitType +'_30.jpg></td><TD width=75px>'+Seed.queue_sacr["city"+cityID][0].quantity+'</td><TD width=50px>'+timestr(Seed.queue_sacr["city"+cityID][0].eta-now)+' ('+timestr(Seed.queue_sacr["city"+cityID][0].eta-Seed.queue_sacr["city"+cityID][0].start)+')</td></tr>';
			if (Seed.queue_sacr["city"+cityID][1]!=undefined) msg+='<TR><TD width=150px>'+Seed.cities[i][1]+' (2)</td><TD width=30px><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+Seed.queue_sacr["city"+cityID][1].unitType +'_30.jpg></td><TD width=75px>'+Seed.queue_sacr["city"+cityID][1].quantity+'</td><TD width=50px>'+timestr(Seed.queue_sacr["city"+cityID][1].eta-now)+' ('+timestr(Seed.queue_sacr["city"+cityID][1].eta-Seed.queue_sacr["city"+cityID][1].start)+')</td></tr>';
		}
		msg += '</table>';
		document.getElementById('SacrificePlaceholder').innerHTML = msg;
	},
	
	clearMarches: function (){
    	var t = Dashboard;
		if (!t.showMarchesInfo) {
			t.showMarchesInfo=true;
			t.ShowMarches();
		} else {
				if (document.getElementById('MarchesInfo')) document.getElementById('MarchesInfo').innerHTML ="";
				document.getElementById('HideMarches').value = ""+culang.mainShow+"";
				t.showMarchesInfo=false;
			}
    },

    ShowRP: function (){
    	var t = Dashboard;
    	var msg = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashRallyPoint\');">'+culang.mainRallyPoint+'</a></div><DIV id="powerDashRallyPoint" style="display:'+Options["powerDashRallyPoint"]+';"><TABLE id=pbRPStats width=100% class=pdxTab><TR>';
		for(b=0; b<Seed.cities.length;b++) {
    		slots = CheckCityMarches(b);
    		rallypointlevel = getRallypoint(Seed.cities[b][0]);
			msg += '<TD>' + uW.roman[b] + ': (' + slots + '/' + rallypointlevel +')</td>';
			if ((b+1)%4==0) msg+='</tr><TR>';
		}
		msg += '</div>';
		ById('ShowRP').innerHTML = msg;
    },

    ShowTrPresets: function (){
    	var t = Dashboard;
    	var msg = '<DIV class="pdxStat"><INPUT id=pbTRHelp type=submit class=pbButton value="HELP">&nbsp; &nbsp; Throne Preset Switcher</div><TABLE id=pbThroneTr width=100% class=pdxTab><TR>';
    	for (i=1;i<=8;i++) {		
    			var total = 0;
    			var active =0;
    			var what="";
    			for (j=1;j<Tabs.Throne.EquipType.length;j++) {
    				what = Tabs.Throne.EquipType[j];
    				id = ThroneOptions.Presets[i][what.toLowerCase()];
    				if (what == "Chair") what = "Throne";
     				if (what == "Windows") what = "Window";
     				if (uW.kocThroneItems[id] != undefined && uW.kocThroneItems[id].isEquipped) active++;
     				if (id > 0) total++;
    			}
    			if (active == total) msg+= '<TD align="center"><B>'+active+'/'+total+'</b></td>';
    				else msg+= '<TD align="center">'+active+'/'+total+'</td>';
    			var stats = renderLocalPresetStats(i);
    			msg+= '<TD><a class=hasTooltip><INPUT type=submit class=pbButton id="Preset_' + i + '" value="'+ThroneOptions.PresetName[i]+'"><SPAN>'+stats+'</span></a></td>';
    			if (i%4==0) msg+='</tr><TR>';
    	}
    	msg += '</tr></table>';
    	msg += '<TABLE class=pdxTab><TR><TD style="width:100px">Kabam presets:</td>';
    	for (var i=1;i<=Seed.throne.slotNum;i++) {
    		msg+='<TD style="width:30px"><a class=hasTooltip><INPUT type=submit class=pbButton id="KabamPreset_' + i + '" value="'+i+'"><SPAN id="KabamPresetHover'+i+'"></span></a></td>';
    	}
    	msg += '</tr></table>';
    	document.getElementById('ShowTrPresets').innerHTML = msg;
    	//for (var i=1;i<=Seed.throne.slotNum;i++) 
    	document.getElementById('pbTRHelp').addEventListener('click', function () {t.helpPop();});
		for (i=1;i<=8;i++) document.getElementById('Preset_' + i).addEventListener ('click', function(){Tabs.Throne.EquipPreset(this.id.substr(7))},false);
		
		for (i=1;i<=Seed.throne.slotNum;i++) {
			if (document.getElementById('KabamPreset_'+i)) document.getElementById('KabamPreset_' + i).addEventListener ('click', function(){Tabs.Throne.EquipKabamPreset(this.id.substr(12))},false);
			if (i==Seed.throne.activeSlot && document.getElementById('KabamPreset_'+i)) document.getElementById('KabamPreset_'+i).setAttribute("class", "pbButton_selected");
			if (i==Seed.throne.activeSlot && document.getElementById('KabamPreset_Chat_'+i)) document.getElementById('KabamPreset_Chat_'+i).setAttribute("class", "pbButton_selected");
			renderKabamPresetStats(i); 
		}
    },
	ShowTrPresetsMini: function (){
    	var t = Dashboard;
    	var msg = '<DIV class="pdxStat">TR Switcher &nbsp; <INPUT id=pbTRHelp type=submit class=pbButton value="?"></div><TABLE id=pbThroneTr width=100% class=pdxTab>';
    	for (i=1;i<=6;i++) {
    			msg+= '<TR><TD><INPUT type=submit class=pbButton id="Preset_' + i + '" value="'+ThroneOptions.PresetName[i]+'"></td>';
    			var total = 0;
    			var active =0;
    			var what="";
    			for (j=1;j<Tabs.Throne.EquipType.length;j++) {
    				what = Tabs.Throne.EquipType[j];
    				id = ThroneOptions.Presets[i][what.toLowerCase()];
    				if (what == "Chair") what = "Throne";
     				if (what == "Windows") what = "Window";
     				if (uW.kocThroneItems[id] != undefined && uW.kocThroneItems[id].isEquipped) active++;
     				if (id > 0) total++;
    			}
    			if (active == total) msg+= '<TD align="center"><B>'+active+'/'+total+'</b></td></tr>';
    				else msg+= '<TD align="center">'+active+'/'+total+'</td></tr>';
    	}
    	msg += '</table>'
    	document.getElementById('ShowTrPresets').innerHTML = msg;
    	document.getElementById('pbTRHelp').addEventListener('click', function () {t.helpPop();});
		for (i=1;i<=6;i++) document.getElementById('Preset_' + i).addEventListener ('click', function(){Tabs.Throne.EquipPreset(this.id.substr(7))},false);
    },
	
	helpPop: function () {
        var helpText = '<DIV style="height:462px;max-height=462px"><BR><B>This DOES work.</b><BR><BR>It just might not do what you think it does.<BR><BR>These are LOCAL presets, it DOES NOT switch the game presets.<BR><BR><U><B>To use this feature...</b></u><BR><BR>1. Go to your AIO and select the Throne tab.<BR><BR>2. Select the Preset subtab.<BR><BR>3. In here you will see local presets that you can rename to whatever you want, eg \'Training\' or \'Range\'.<BR><BR>4. Once named, switch to the \'Compare\' subtab. These are all your cards.<BR><BR>5. Click on any of the titles of the cards. This opens a popup window where you can equip, add to preset, add to update or enhance queue.<BR><BR>6. Once you add it to a preset, go back to the \'Preset\' subtab.<BR><BR>7. You should now see your card in the preset you added it to.<BR><BR>8. Refresh <BR><BR> 9.Click on the \'Quick TR Switcher\' button on the dashboard for those cards to be equipped automatically.</div>';
        var pop = new CPopup('giftHelp', 0, 0, 425, 485, true);
        pop.centerMe(mainPop.getMainDiv());
        pop.getMainDiv().innerHTML = helpText;
		pop.getTopDiv().innerHTML = '<DIV class="popupBanner">TR Switcher Help</DIV>';

        pop.show(true);
	},

	ShowAutoTrain: function (){
    	var t = Dashboard;
    	var msg = '<DIV class="pdxStat">Auto Train</div>';
		var now = unixTime();
		if (!TrainOptions.Running) msg+="Auto Train is OFF";
			else {
				if (Tabs.AutoTrain.trainTime > now) msg += "Doing Train cycle (Set Preset/Train Troops/Reset TR Items) for: " + timestr(Tabs.AutoTrain.trainTime - now);
					else if (Tabs.AutoTrain.nextround > now) msg += "Next Auto Train cycle in: " + timestr(Tabs.AutoTrain.nextround - now);
		}
 		document.getElementById('ShowAutoTrain').innerHTML = msg;
    },

    ShowTowerAlerts: function (){
    	var t = Dashboard;
    	var NoAttack = true;
    	for (k in Seed.queue_atkinc) if (Seed.queue_atkinc[k].marchType == 3 || Seed.queue_atkinc[k].marchType ==4) NoAttack = false;
    	if (NoAttack) {
    		document.getElementById('TowerAlertPlaceholder').innerHTML = "";
    		return;
    	}
    	document.getElementById('TowerAlertPlaceholder').innerHTML = '<BR><DIV class="pbStatRed">Tower Alerts</div><DIV id=ShowTowerAlerts></div>'; //style="height: 100px; overflow: auto">
    	var msg = '';
    	var action = '';
    	var arrivalTime = 0;

    	for(k in Seed.queue_atkinc) {
    		var now = unixTime();
    		var counter = 0;

    		if (Seed.queue_atkinc[k].fromPlayerId != uW.tvuid && Seed.queue_atkinc[k].arrivalTime > now) {
				for (postcity in Seed.cities) if (Seed.cities[postcity][0] == Seed.queue_atkinc[k].toCityId) cityName = Seed.cities[postcity][1];
				if (Seed.queue_atkinc[k].marchType == 3) action = ""+culang.mainScout+"";
				if (Seed.queue_atkinc[k].marchType == 4) action = ""+culang.mainAttack+"";
				arrivalTime = Seed.queue_atkinc[k].arrivalTime - now;
				msg += cityName + ': ' + action + ' -- '+culang.shortETA+': ' + timestr(arrivalTime);
				msg +='<BR><TABLE class=pdxTab><TR>';
				for (i=1;i<=17;i++){
					if (Seed.queue_atkinc[k]["unts"] == undefined) {
						msg +='<TR><TD>???</td></tr>'; 
					} else if (parseInt(Seed.queue_atkinc[k]["unts"]["u"+i]) > 0) {
						if (counter%4==0) msg+='</tr><TR>';
						counter++;
						msg+='<TD width=30><img src=http://www352.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30.jpg></td><TD width=80>' + Seed.queue_atkinc[k]["unts"]["u"+i] + '</td>';
					}
				}
				msg+='</tr></table>';
			}

    	}
    	document.getElementById('ShowTowerAlerts').innerHTML = msg;
    },

    RPM: function (){
    	var t = Dashboard;
    	var now=unixTime();
        var time = 0;
        var calc = 0
        time = now - RPMtime;   
        calc =(RPM/time)*60;
        calc = Math.round(calc);
        if (time <30) calc = "...";
		ById('dbHeader').innerHTML = '<b><i>'+culang.dashboard_head_request+'</b> <span class=boldRed>' + calc + '</span></i> - <b><i>'+culang.dashboard_head_request2+'</b> <span class=boldRed><SPAN id=MouseMove title="'+culang.dashboard_head_moveMove+'"></span></span></i>'; 
		},

    CityStatus: function (){
    	var t = Dashboard;
    	var msg = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashCityStatus\');">'+culang.dashboard_head_cityDef+'</a></div><DIV id="powerDashCityStatus" style="display:'+Options["powerDashCityStatus"]+';"><TABLE id=pbRPStats width=100% class=pdxTab><TR>';
    	for(b=0; b<Cities.numCities; b++) msg+= '<TD><INPUT type=submit id="cityDEF_' + Seed.cities[b][0] + '" value="'+uW.roman[b]+'"></td>';
		msg += '</div>';
    	document.getElementById('CityStatus').innerHTML = msg;
    	for(b=0; b<Cities.numCities; b++) {
    		if (parseInt(Seed.citystats["city" + Seed.cities[b][0]].gate) == 0) document.getElementById('cityDEF_' + Seed.cities[b][0]).style.backgroundColor  = "green";
    			else document.getElementById('cityDEF_' + Seed.cities[b][0]).style.backgroundColor  = "red";
    		document.getElementById('cityDEF_' + Seed.cities[b][0]).style.color  = "white";
    		document.getElementById('cityDEF_' + Seed.cities[b][0]).addEventListener ('click', function(){
	    		var city = this.id.substr(8);
	    		if (parseInt(Seed.citystats["city" + city].gate) == 0) t.ChangeDefMode(city,1);
	    		if (parseInt(Seed.citystats["city" + city].gate) == 1) t.ChangeDefMode(city,0);
      		},false);
    	}    	
    },

	multiNote: function (){
    	var t = Dashboard;
    	var msg = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashMutli\');">'+ScriptName+'</a></div>\
				<DIV id="powerDashMutli" style="display:'+Options["powerDashMutli"]+';">\
	<table width="369" height="124" border="0" cellpadding="0" cellspacing="0" class=pdxTab>\
  <tr><td height="19" colspan="3"><a href="'+homePage+'" target="_blank"><img src="'+IMGpowerDashLogo+'"></a></td></tr>\
    <tr>\
    <td height="19"><b><u>'+culang.options_dashboard_multinote_script+'</u></b></td>\
     <td width="201" colspan="2"><a href="http://kocscripts.com/work/koc-power-multilang" target="_blank">'+culang.options_dashboard_multinote_script2+'</a> <sup><span class=boldRed>('+KsScriptRunning+')</span></sup></td>\
  </tr>\
  <tr>\
    <td height="19"><b><u>'+culang.options_dashboard_multinote_version+'</u></b></td>\
     <td colspan="2"><span class=shadowCaps>'+Version+'</span></td>\
  </tr>\
  <tr>\
    <td width="168" height="19"><b><u>'+culang.options_dashboard_multinote_langversion+'</u></b></td>\
    <td colspan="2"><span class=shadowCaps>'+LangpackVersion+'</span></td>\
  </tr>\
  <tr>\
    <td width="168" height="19"><a href="'+homePage+'/forum">'+culang.options_dashboard_multinote_forum+'</a></td>\
    <td colspan="2"></td>\
  </tr>\
  <tr>\
    <td height="19">&nbsp;</td>\
    <td colspan="2">&nbsp;</td>\
  </tr>\
  <tr>\
    <td height="19"><b><u>'+culang.options_dashboard_multinote_update+'</u><b></td>\
    <td colspan="2"></td>\
  </tr>\
  <tr>\
    <td colspan="3">'+culang.options_dashboard_multinote_update2+' '+KsScriptRunning+' '+culang.options_dashboard_multinote_update3+'</td>\
  </tr>\
  <tr>\
    <td colspan="3">'+KsLatestVersion+'</td>\
	</tr>\
	<tr><td colspan="3"><BR></td></tr>\
  <tr>\
  </tr>\
	<tr><td colspan="3"></td></tr>\
  <tr>\
    <td colspan="3">[ <a href="#" onClick="KsSaveCategorys(\'powerDashMutliInstallLinks\');">'+culang.options_dashboard_multinote_install+'</a> ]\
	<div id=powerDashMutliInstallLinks style="display:'+Options["powerDashMutliInstallLinks"]+';>\
	<span style="witdh: 10px;"></span>'+culang.options_dashboard_multinote_install2+'\
	<BR>'+culang.options_dashboard_multinote_install3+'\
	</div></td>\
  </tr>\  <tr>\
    <td height="19">[ <a href="#" onClick="KsSaveCategorys(\'powerDashMutliLinks\');">'+culang.options_dashboard_multinote_links+'</a> ]</td>\
    <td colspan="2">&nbsp;</td>\
  </tr>\
  <tr>\
    <td colspan="3"><div id=powerDashMutliLinks style="display:'+Options["powerDashMutliLinks"]+';>\
         <span style="witdh: 10px;"></span>\
                        <a href="http://koc-power-all.webs.com/" target="_blank"><img src="'+IMGpdxTeam+'" alt="KoC Scripts" width="32" height="32" border="0" title="'+culang.KsInfoBoxHomePageNote+'"></a>\
                        <a href="http://koc-power-all.webs.com/apps/forums/" target="_blank"><img src="'+IMGteamLink+'" alt="KS Team" width="32" height="32" border="0" title="'+culang.KsInfoBoxTeamNote+'"></a>\
                        <a href="http://www.facebook.com/groups/TheEliteFew/" target="_blank"><img src="'+IMGdevGroup+'" alt="KS DevGroup" width="32" height="24" border="0" title="'+culang.KsInfoBoxDevGroupNote+'"></a>\
                        <a href="http://koc-power-all.webs.com/apps/profile/" target="_blank"><img src="'+IMGFBGroup+'" alt="Facebook Groups" width="32" height="32" border="0" title="'+culang.KsInfoBoxFacebookNote+'"></a>\
                        <a href="http://code.google.com/p/mad-hatters-magic-elite/" target="_blank"><img src="'+IMGgooglecode+'" alt="googlecode" width="32" height="32" border="0" title="'+culang.KsInfoBoxGCNote+'"></a>\
                        <a href="http://code.google.com/p/mad-hatters-magic-elite/issues/entry?show=review&former=sourcelist" target="_blank"><img src="'+IMGuserscripts+'" alt="Userscripts" width="32" height="32" border="0" title="'+culang.KsInfoBoxUserscriptsNote+'"></a>\
                        <a href="http://code.google.com/p/mad-hatters-magic-elite/issues/entry" target="_blank"><img src="'+IMGreport+'" alt="Report" width="32" height="32" border="0" title="'+culang.KsInfoBoxReportNote+'"></a>\
                        <a href="http://userscripts.org" target="_blank"><img src="'+IMGreview+'" alt="Review" width="32" height="32" border="0" title="'+culang.KsInfoBoxReviewNote+'"></a>\
                        <a href="http://www.mozilla.org/firefox/" target="_blank"><img src="'+IMGfirefox+'" alt="Firefox" width="32" height="32" border="0" title="'+culang.KsInfoBoxFirefoxNote+'"></a>\
                        <a href="https://addons.mozilla.org/de/firefox/addon/greasemonkey/" target="_blank"><img src="'+IMGgreasemonkey+'" alt="Greasemonkey" width="32" height="32" border="0" title="'+culang.KsInfoBoxGreasemonkeyNote+'"></a>\
                        <a href="https://addons.mozilla.org/de/firefox/addon/scriptish/" target="_blank"><img src="'+IMGscriptish+'" alt="Scriptish" width="32" height="32" border="0" title="'+culang.KsInfoBoxScriptishNote+'"></a>\
                        <a href="http://www.java.com/de/download/installed.jsp" target="_blank"><img src="'+IMGjava+'" alt="Java" width="32" height="32" border="0" title="'+culang.KsInfoBoxJavaNote+'"></a>\
                        <a href="http://www.adobe.com/de/software/flash/about/" target="_blank"><img src="'+IMGflash+'" alt="FlashPlayer" width="32" height="32" border="0" title="'+culang.KsInfoBoxFlashNote+'"> </a>\
                        <a href="http://www.4loot.com/?id=264098&src=em" target="_blank">  <img src="'+IMG4loot+'" alt="4Loot" width="30" height="30" border="0" title="'+culang.KsInfoBox4LootNote+'"> </a>\
                        </div><BR>\
	</td>\
  </tr>\
</table>';

		msg += '</div>';
    	document.getElementById('MultiDashNote').innerHTML = msg;  	
    },

    ChangeDefMode : function (cityId, state){
    	var t = Dashboard;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.cid = cityId;
        params.state = state;
        
        new MyAjaxRequest(uW.g_ajaxpath + "ajax/gate.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    Seed.citystats["city" + cityId].gate = state;
                    if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
                }
            },
            onFailure: function () {
            }
        })
  	},

  	ShowLog: function (){
  		var t = Dashboard;
  		var msg = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashLog\');">'+culang.tabLabelActionLog+'</a></div><DIV id="powerDashLog" style="display:'+Options["powerDashLog"]+';">';
		var amount = parseInt(Tabs2.ActionLog.last250.length)-1;
  		for (i=amount;i>(amount-5);i--) if (Tabs2.ActionLog.last250[i] != undefined) msg+= Tabs2.ActionLog.last250[i].ts + '- <b>'  + Tabs2.ActionLog.last250[i].ou + '</b>: '+ Tabs2.ActionLog.last250[i].msg + '<BR>';
		msg += '</div>';
  		document.getElementById('ShowLog').innerHTML = msg;
    
    },

    ShowTroops: function (){
    	var t = Dashboard;
    	var msg = '<DIV class=pdxStat><a href="#" onclick="KsSaveCategorys(\'powerDashTroops\');">'+culang.mainTroops+'</a></div><DIV id="powerDashTroops" style="display:'+Options["powerDashTroops"]+';">';
    	msg+= '<SPAN id=dbCityCel></span>&nbsp&nbsp&nbsp<INPUT type=submit class=pbButton id="HideTroops" value="'+culang.mainHide+'"><BR><DIV id=dbCityInfo></div></div>';
		document.getElementById('ShowTroops').innerHTML = msg;  	
    	t.tcp = new CdispCityPicker ('dbCityCelBut', document.getElementById('dbCityCel'), true, t.PaintTroops);
    	document.getElementById('HideTroops').addEventListener ('click', function(){document.getElementById('dbCityInfo').innerHTML = "";t.tcp = new CdispCityPicker ('dbCityCelBut', document.getElementById('dbCityCel'), true, t.PaintTroops)},false);	
    },
		
    PaintTroops: function (){
    	var t = Dashboard;
    	var info ='<TABLE id=pbRPStats width=100% class=pdxTab><TR>';
    	for (l in Seed.units['city' + t.tcp.city.id]) {
    		info+= '<TD style="width: 30px;"><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+ l.substr(3) +'_30.jpg></td><TD style="vertical-align: middle;">' + addCommas(Seed.units['city' + t.tcp.city.id][l]) +'</td>';
    		if (l.substr(3)%4==0) info+='</tr><TR>';
    	}
    	document.getElementById('dbCityInfo').innerHTML = info;
    },

    show:function (){},    
    hide:function (){}
}
// VAR AUTOREPAIR
var RepairAuto = {
	timer : null,
	repairtimer: null,
	init: function (){
		if (!Options.salvageconfig.Repairrunning) return;
		if (upgradeData.active == true) {
			upgradeData.active = false;
			saveUpgradeData();
			//return;
		}
		RepairAuto.setEnable();
	},
	setEnable: function (){
		var t = RepairAuto;
		clearTimeout (t.repairtimer);
		t.tableau=[];
		t.repairtimer = setTimeout (t.count, 1*1000);
	},

	count:function() {
		var t = RepairAuto;
		var lignauto = Seed.throne.rowNum * 5, i=uW.kocThroneItems;
		var nbl=0;
		t.tableau=[];
		clearTimeout (t.repairtimer);
		if (!Options.salvageconfig.Repairrunning) return;

		for (var z in i) {
			if (i[z].id) {
				e=uW.kocThroneItems[i[z].id];
				if (e) {
					nbl++;
					if (e.isBroken && nbl<=lignauto ) {
						if (Seed.queue_throne) {
							if (Seed.queue_throne.itemId!=e.id)
								t.tableau.push(i[z].id);
						} else {
							t.tableau.push(i[z].id);
						}
					}
				}
			}
		}
		var timeLeft=-1;
		if (Seed.queue_throne) {
			if (Seed.queue_throne.end)
				timeLeft = Seed.queue_throne.end - uW.unixtime();
		}
		if (t.tableau.length>0 && timeLeft<0) {
			var itemId = t.tableau[Math.floor(Math.random()*t.tableau.length)];
			actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairOK+" " + uW.kocThroneItems[itemId].name + " "+culang.throneStuffRepairOK2+" " + t.tableau.length + "");
			t.repair(itemId);
		} else {
			if (timeLeft>0) {
				actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairAlready+" "+timeLeft+""+culang.throneStuffRepairAlready2+"");
				t.repairtimer = setTimeout (t.count, (timeLeft+5)*1000);
			} else {
				actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffNoItemToDelete5Min+"");
				t.repairtimer = setTimeout (t.count, (5*60)*1000);
			}
		}
	},

	repairId:0,
	repariend:null,
	countRepair:0,
	clearRepair:function() {
		var t = RepairAuto;
		if (t.repairId != 0) {
			uW.kocThroneItems[t.repairId].isBroken = false;
			uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
			t.repairId = 0;
		}
	},
	repair: function(id) {
		var t = RepairAuto;
		clearTimeout (t.repairtimer);
		if (!Options.salvageconfig.Repairrunning) return;
		if (uW.kocThroneItems[id]) {
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.action="timeRepair";
			params.ctrl="throneRoom\\ThroneRoomServiceAjax";
			params.throneRoomItemId=id;
			uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
				onSuccess:function(transport) {
					var m = eval("(" + transport.responseText + ")");
					if (m.ok === true){
						Seed.queue_throne.start = uW.unixtime();
						Seed.queue_throne.end = m.eta; //uW.unixtime() + L;
						Seed.queue_throne.itemId = id;
						t.repairId = id;
						t.repairend = m.eta;
						uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
						var x = m.eta - unixTime();
						setTimeout(t.clearRepair, (x+1)*1000);
						t.countRepair=0;
						duree= Seed.queue_throne.end - Seed.queue_throne.start + 5;
						actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairOK+" " + uW.kocThroneItems[id].name + " "+culang.throneStuffRepairOK2+" " +duree +""+culang.shortSeconds+"");
						t.repairtimer = setTimeout (t.count, (duree)*1000);
					} else {
						t.countRepair++;
						actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairError+" " + uW.kocThroneItems[id].name);
						if (t.countRepair>5) {
							t.countRepair=0;
							t.repairtimer = setTimeout (t.count, (2*60)*1000);
						} else {
							setTimeout(function() { t.repair(id); },2000);
						}

					}
				}
			});

		} else {
			actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairNoID+"");
			t.repairtimer = setTimeout (t.count, (2*60)*1000);
		}
	},
}
// VAR MESSAGENAV
var messageNav = {
	mmFunc : null,
	MapFunc :null,
	mmsFunc : null,
	init : function (){
		t = messageNav;
		t.MapFunc = new CalterUwFunc ('modal_maptile', [[/}\s*$/, ';setTimeout(function() { KsMdal_hook(j); },0); }']]);
		//t.mmFunc = new CalterUwFunc ('modal_messages', [[/}\s*$/, ';setTimeout(messageNav_hook,0); }']]);
		//t.mmsFunc = new CalterUwFunc ('modal_messages_send', [[/{\s*var params/i, '{if (modal_messages_send_hook()) return; var params']]);
		uW.KsMdal_hook = t.testons;
		//uW.messageNav_hook = t.hook;
		//uW.modal_messages_send_hook = t.msgSendHook;
		t.MapFunc.setEnable (true);
		//t.mmFunc.setEnable (true);
		//t.mmsFunc.setEnable (true);

	},
	setEnable : function (tf){
	},
	isAvailable : function (){
		t = messageNav;
		return t.mmFunc.isAvailable();
	},
	testons :function(uid) {
		if (uid!=null && uid > 0) {
			var div = ById('contextMenu');
			var scr = document.createElement('div');
			scr.style.padding = "5px";
			scr.innerHTML =""+culang.movementPlayerCheckSearch+"";
			div.appendChild(scr);
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.checkArr = uid;
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/getOnline.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					var p = rslt.data;
					if (p[uid] == true) {
						m = '<span style="color:green; font-weight:bold;">'+culang.movementPlayerCheckOn+'</span>';
						scr.innerHTML= m;
					} else {
						m = '<span style="color:maroon; font-weight:bold;">'+culang.movementPlayerCheckOff+'</span>';
						scr.innerHTML= m;
						var params = uW.Object.clone(uW.g_ajaxparams);
						params.pid = uid;
						new MyAjaxRequest(uW.g_ajaxpath + "ajax/viewCourt.php" + uW.g_ajaxsuffix, {
							method: "post",
							parameters: params,
							onSuccess: function (rslt) {
								if (rslt.ok) {
									scr.innerHTML += '<br><u>'+culang.mainLastLogin+'</u>:<br>'+rslt.playerInfo.lastLogin+'';
								}

							},onFailure: function (rslt) {},

						});

					}
				},onFailure: function (rslt) {},
			});
		}
	},
	hook : function (){
		if (!Options.enhanceMsging)
			return;
		var div = ById('modal_msg_view_actions');
		div = ById('modal_msg_write_to').parentNode;
		div.innerHTML = '<TABLE><TR><TD class=xtab><b>A: </b> <INPUT type=text id=modal_msg_write_to></td>\
    <TD class=xtab></td></tr>\
    <tr><td></td><td></td></tr></table>\
    <table><tr><TD colspan=2><SPAN id=pt2fwdbut></span></td></tr></table>';
		ById('pt2fwdbut').innerHTML="CC: <INPUT type=text id=message_cc>";
	},
	eventForward : function (){
		ById('modal_msg_write_subj').value = "TR: " + ById('modal_msg_view_subj').innerHTML.toString().stripTags();
		ById('modal_msg_write_to').value = '';
		var from = ById('modal_msg_view_from').children[0].innerHTML;
		var body = ById('modal_msg_view_body').innerHTML.replace(/\n/g, '').replace(/<br>/gi, '\n').stripTags().replace (/back$/i, '');
		ById('modal_msg_write_txt').value = '[Nachricht orginal von: '+ from +']\n'+ body;
		uW.modal_messages_compose();
	},
	msgSendHook : function (){
		if (!Options.enhanceMsging)
			return;
		var to = ById("modal_msg_write_to").value.trim();
		var chaine = ById("message_cc").value;
		var tableau = chaine.split(";")
		if (tableau.length==0) tableau[0]=chaine;
		for (var i = 0; i < tableau.length; i++) {
			var params = uW.Object.clone(uW.g_ajaxparams);
			params.emailTo = tableau[i] ;
			params.subject = "CC: "+ById("modal_msg_write_subj").value;
			params.message = ById("modal_msg_write_txt").value;
			params.requestType	 = 'COMPOSED_MAIL';
			new MyAjaxRequest(uW.g_ajaxpath + "ajax/getEmail.php" + uW.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					if (rslt.ok) ById('message_cc').value = "";
				},
			});
		}
		if (to.toLowerCase() != '<officiers>' || getMyAlliance()[0]==0) {
			return false;
		}
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.toIds = getMyAlliance()[0];
		params.subject = ById("modal_msg_write_subj").value +'';
		params.message = ById("modal_msg_write_txt").value;
		params.type = 'alliance';
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/sendMessage.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					uW.Modal.showAlert(uW.g_js_strings.modal_messages_send.msgsent);
					ById('modal_msg_write_to').value = "";
					ById('modal_msg_write_subj').value = "";
					ById('modal_msg_write_txt').value = ""
				} else {
					uW.Modal.showAlert(uW.g_js_strings.modal_messages_send.enterexistingname)
				}
			},
			onFailure: function () {
				uW.Modal.showAlert(uW.g_js_strings.modal_messages_send.oopscompose)
			},
		});
		return true;
	},
}
// VAR ATTACKDIALOG
var AttackDialog = {
	init : function (){
		var t = AttackDialog;
		t.modal_attackFunc = new CalterUwFunc ('modal_attack', [[/}\s*$/, ';attackDialog_hook(); }']]);
		uW.attackDialog_hook = t.modalAttackHook;
		t.modal_attackFunc.setEnable (true);
	},

	setEnable : function (){
	},

	isKnightSelectAvailable : function (){
		var t = AttackDialog;
		return t.modal_attackFunc.isAvailable();
	},
	isAttackCityPickerAvailable : function (){
		var t = AttackDialog;
		return t.modal_attackFunc.isAvailable();
	},

	modalAttackHook : function (){
		var t = AttackDialog;
		if (Options.fixKnightSelect || Options.attackCityPicker){
			for (var i=1; i<6; i++)
				ById('modal_attack_tab_'+ i).addEventListener('click', t.e_changeMarchType, false);
		}
		if (Options.attackCityPicker){
			setTimeout (t.initCityPicker, 0);
		}
	},

	initCityPicker : function (){
		var t = AttackDialog;
		var div = ById('modal_attack_target_numflag'); // as of KofC version 96;
		var mySpan;
		if (div) {
			div.parentNode.innerHTML += ' &nbsp; <SPAN id=modal_attack_citybuts></span>';
		} else {
			var span = ById('modal_attack_target_coords');   // KofC version 116+;
			span.parentNode.parentNode.firstChild.innerHTML += ' &nbsp; <SPAN id=modal_attack_citybuts></span>';
		}
		new CdispCityPicker ('ptatp', ById('modal_attack_citybuts'), false, t.e_CityButton);
		var cityIdx = Cities.byID[uW.currentcityid].idx;
		thisCityBut = ById('ptatp_'+ cityIdx);
		thisCityBut.style.opacity = '0.5';
		thisCityBut.disabled = true;
		if (ById('modal_attack_tab_4').className=='selected' || ById('modal_attack_tab_3').className=='selected')   // don't do for attack or scout
			ById('modal_attack_citybuts').style.display = 'none';
	},

	e_CityButton : function (city){
		ById('modal_attack_target_coords_x').value = city.x;
		ById('modal_attack_target_coords_y').value = city.y;
		uW.modal_attack_update_time();
	},

	e_changeMarchType : function (evt){
		var t = AttackDialog;
		var marchType = parseInt(evt.target.id.substr(17));
		if (Options.attackCityPicker){
			if (marchType==3 || marchType==4)
				ById('modal_attack_citybuts').style.display = 'none';
			else
				ById('modal_attack_citybuts').style.display = 'inline';
		}
		if (Options.fixKnightSelect){
			var knightVal = 0;
			var selector = ById('modal_attack_knight');
			if (selector.length>1 && (marchType==4 || marchType==2))   // if 'attack' or 'reinforce'
				knightVal = 1;
			selector.selectedIndex = knightVal;
		}
	},
}
// VAR DISPREPORT
var DispReport = {
	init : function (){
		var t = DispReport;
		t.modal_InboxFunc = new CalterUwFunc ('modal_messages_listshow', [['msghtml.join("");', 'msghtml.join("");dispInbox_hook(rslt,boxType,msghtml);']]);
		uW.dispInbox_hook = t.ModalInboxHook;
		t.modal_InboxFunc.setEnable (Options.enhancedinbox);
	},

	setEnable : function (tf){
		var t = DispReport;
		t.modal_InboxFunc.setEnable (tf);
	},

	isDispReportAvailable : function (){
		var t = DispReport;
		return t.modal_InboxFunc.isAvailable();
	},

	ModalInboxHook : function (rslt,boxType,msghtml){
		var t = DispReport;
		if(boxType == 'inbox'){
			msgBody = document.getElementById('modal_msg_list');
			var a = document.createElement('a');
			a.className='inlineButton20Red';
			a.innerHTML='<span>'+culang.giftsDeleteReports+'</span>';
			a.style.float = 'left';
			a.style.position = 'relative';
			a.style.top = '10px';
			a.style.left = '25px';
			a.addEventListener('click', t.checkinbox, false);
			var div = document.createElement('span');
			div.appendChild(a);
			msgBody.appendChild(div);
		}
	},

	checkinbox : function(evt){
		var t = DispReport;
		var body = document.getElementById('tbl_messages');
		var trs=body.getElementsByTagName('tr');
		var reports = [];
		for(var i=0; i<trs.length; i++){
			var tds = trs[i].getElementsByTagName('td');
			for(var j=0; j<tds.length; j++){
				if(tds[j].className == 'chkcol'){
					var checkbox = tds[j];
				}
				if(tds[j].className == 'nmcol'){
					var sender = tds[j];
				}
				if(tds[j].className == 'subjcol'){
					var subject = tds[j];
				}
			}
			reports.push({checkbox:checkbox,sender:sender,subject:subject});
		}
		t.parseGiftReport(reports);
	},

	parseGiftReport : function(rpts){
		var t = DispReport;
		for(var i=0; i<rpts.length; i++){
			if((rpts[i].subject.innerHTML.indexOf(''+culang.getGiftDeleteButton+'') >= 0 ||
					rpts[i].subject.innerHTML.indexOf('New Gift Received!') >= 0 ||
					rpts[i].subject.innerHTML.indexOf('Neues Geschenk erhalten!') >= 0 ||
					rpts[i].subject.innerHTML.indexOf('Nouveaux Cadeaux') >= 0 ||
					rpts[i].subject.innerHTML.indexOf('Nuevo regalo recibido') >= 0 ||
					rpts[i].subject.innerHTML.indexOf('Nuovo Regalo ricevuto') >= 0 
				) && 
				rpts[i].sender.innerHTML.indexOf('Kingdoms Of Camelot') >= 0
			){
				rpts[i].checkbox.firstChild.checked = true;
			}
		}
		uW.messages_action("delete","tbl_messages");
	}

}
// VAR ALLIANCE REPORTS
var AllianceReports = {
	checkPeriod : 300,
	allianceNames : [],
	saveArfunc : uW.allianceReports,
	
	init : function (){
		t = AllianceReports;
		t.enable (Options.enhanceARpts);
		t.marvFunc = new CalterUwFunc ('modal_alliance_report_view', [['getReportDisplay', 'getReportDisplay_hook2']]);
		t.memListFunc = new CalterUwFunc ('membersInfo', [['commonstr.might','commonstr.might + "</td><td class=colcities>" + g_js_strings.commonstr.cities + "</td><td class=colava>Avatar</td><td class=collast>" + g_js_strings.membersInfo.lastonline'],['memberInfo[key].prestige)', 'memberInfo[key].prestige)+ "</td>");memhtml.push("<td class=colcities>" + memberInfo[key].cities + "</td><td class=colava><img width=35 src=" + memberInfo[key].avatarurl + "></td>");memhtml.push("<td class=collast>" + memberInfo[key].lastLogin']]);

		uW.getReportDisplay_hook2 = t.getReportDisplayHook;
		uW.getmembersInfo_hook = t.getMembersInfoHook;
		t.marvFunc.setEnable (true);
		t.enable_viewmembers(Options.enhanceViewMembers);
	},
	getReportDisplayHook : function (a, b){
		var x = '';
		try {
			x = uW.getReportDisplay(a,b);
		} catch (e){
			x = 'Error formatting report: '+ e;
		}
		return x;
	},
	enable_viewmembers : function (tf){
		t = AllianceReports;
		t.memListFunc.setEnable (tf);
	},
	enable : function (tf){
		t = AllianceReports;
		if (tf)
			uW.allianceReports = t.myAllianceReports;
		else
			uW.allianceReports = t.saveArfunc;
	},
	myAllianceReports : function (pageNum){
		var params = uW.Object.clone(uW.g_ajaxparams);
		if (pageNum)
			params.pageNo = pageNum;
		params.group = "a";
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/listReports.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				displayReports (rslt.arReports, rslt.arPlayerNames, rslt.arAllianceNames, rslt.arCityNames, rslt.totalPages);
			},
			onFailure: function (rslt) {
			},
		}, false);

		function displayReports (ar, playerNames, allianceNames, cityNames, totalPages){
			var msg = new Array();
			var myAllianceId = getMyAlliance()[0];
			msg.push ("<STYLE>.msgviewtable tbody .myCol div {margin-left:5px; overflow:hidden; white-space:nowrap; color:#000}\
            .msgviewtable tbody .myHostile div {color:#900}\
            .msgviewtable tbody .myGray div {color:#666}\
            .msgviewtable tbody .myRein div {color:#090}\
            .msgviewtable tbody .myWarn div {color:#442200}\
            </style>");
			msg.push("<div class='modal_msg_reports'>");
			var rptkeys = uW.Object.keys(ar);
			if (matTypeof(ar) != 'array') {
				if (Options.allowAlterAR)
					msg.push("<div id='modal_alliance_reports_tablediv' class='modal_msg_list'><table width=675 cellpadding='0' cellspacing='0' class='msgviewtable reportviewtable alliancetable'>");
				else
					msg.push("<div id='modal_alliance_reports_tabledivNKA' class='modal_msg_list'><table width=675 cellpadding='0' cellspacing='0' class='msgviewtable reportviewtable alliancetable'>");
				msg.push("<thead><tr><td width=105>"+culang.mainDate+"</td><td width=40>"+culang.mainType+"</td><td width=150>"+culang.mainAttacker+"</td><td>"+culang.mainTarget+"</td><td>"+culang.mainShow+"</td>");
				//msg.push("<td>"+culang.shortDistance+"</td>");
				msg.push("</tr></thead><tbody>");
				for (var i = 0; i < rptkeys.length; i++) {
					var rpt = ar[rptkeys[i]];
					var colClass = '"myCol"';
					rpt.marchType = parseInt(rpt.marchType);
					rpt.side0AllianceId = parseInt(rpt.side0AllianceId);
					var targetDiplomacy = getDiplomacy (rpt.side0AllianceId);
					if (rpt.marchType == 2){
						colClass = '"myCol myRein"';
					} else if (rpt.side1AllianceId != myAllianceId){
						colClass = '"myCol myHostile"';
					} else {
						if (parseInt(rpt.side0TileType) < 50){          // if wild
							if (parseInt(rpt.side0PlayerId) == 0)
								colClass = '"myCol myGray"';
							else
								colClass = '"myCol myWarn"';
						} else if (parseInt(rpt.side0PlayerId) == 0) {   // barb
							colClass = '"myCol myGray"';
						} else {
							if (targetDiplomacy == ''+culang.kocFriendly+'')
								colClass = '"myCol myWarn"';
						}
					}
					msg.push ('<tr valign=top');
					if (i%2 == 0)
						msg.push(" class=stripe");
					msg.push("><TD class="+ colClass +"><div>");
					msg.push(uW.formatDateByUnixTime(rpt.reportUnixTime));
					msg.push ('<BR>Rpt #');
					msg.push (rpt.reportId);
					msg.push("</div></td><TD class="+ colClass  +"><div>");
					if (rpt.marchType == 1)
						msg.push (uW.g_js_strings.commonstr.transport);
					else if (rpt.marchType == 3)
						msg.push (uW.g_js_strings.commonstr.scout);
					else if (rpt.marchType == 2)
						msg.push (culang.mainReinforced);
					else
						msg.push (uW.g_js_strings.commonstr.attack);
					msg.push ("</div></td><TD class="+ colClass +"><div>");
					if (parseInt(rpt.side1PlayerId) != 0)
						msg.push('<a onclick=getInfoForAnUser("'+parseInt(rpt.side1PlayerId)+'");>'+escape(playerNames["p" + rpt.side1PlayerId])+"</a>");
					else
						msg.push ('?'+culang.mainUnknown+'?');
					msg.push ('&nbsp;<a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a><bR>');
					if (rpt.side1AllianceId != myAllianceId){
						msg.push (allianceNames['a'+rpt.side1AllianceId]);
						msg.push (' (');
						msg.push (getDiplomacy(rpt.side1AllianceId));
						msg.push (')');
					} else {
						msg.push ('<BR>');
					}
					msg.push ('</div></td>');
					msg.push ("<TD class="+ colClass  +"><DIV>");
					var type = parseInt(rpt.side0TileType);
					if (type < 50){                              // pour la TS
						msg.push(uW.g_mapObject.types[type].toString().capitalize());
						msg.push(" "+culang.shortLevel+" " + rpt.side0TileLevel)
						if (parseInt(rpt.side0PlayerId) != 0) {   // IF OWNED, show owner ...
							msg.push (' [');
							msg.push ('<a @onclick=getInfoForAnUser("'+parseInt(rpt.side0PlayerId)+'");>' + escape(playerNames["p" + rpt.side0PlayerId])+'</a>');
							msg.push ('] ');
						}
					} else {
						if (parseInt(rpt.side0PlayerId) == 0) {   //  barb
							msg.push(uW.g_js_strings.commonstr.barbariancamp);
							msg.push(" "+culang.shortLevel+" " + rpt.side0TileLevel)
						} else {        // city
							msg.push ('<a onclick=getInfoForAnUser("'+ rpt.side0PlayerId+'");>' + escape(playerNames["p" + rpt.side0PlayerId])+'</a>');
							msg.push (' - ');
							msg.push (cityNames['c'+ rpt.side0CityId]);
						}
					}
					msg.push ('&nbsp;<a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a>');
					if (rpt.side0AllianceId!=0 && rpt.side0AllianceId!=myAllianceId){
						msg.push ('<BR>');
						msg.push (allianceNames['a'+rpt.side0AllianceId]);
						msg.push (' (');
						msg.push (targetDiplomacy);
						msg.push (')');
					}
					if (Options.allowAlterAR)
						msg.push("</div></td><TD class="+ colClass  +"><div><a onclick=' modal_alliance_report_view(\"");   // ONCLICK ???
					else
						msg.push("</div></td><TD class="+ colClass  +"><div><a onclick=' ById(\"modal_alliance_reports_tabledivNKA\").id=\"modal_alliance_reports_tablediv\"; modal_alliance_report_view(\"");   // ONCLICK ???
					msg.push(rpt.reportId);
					msg.push('",');
					if (parseInt(rpt.side1AllianceId) == parseInt(Seed.allianceDiplomacies.allianceId))
						msg.push(1);
					else
						msg.push(0);
					msg.push(",");
					msg.push(rpt.side0TileType);
					msg.push(",");
					msg.push(rpt.side0TileLevel);
					msg.push(",");
					msg.push(rpt.side0PlayerId);
					msg.push(',"');
					if (parseInt(rpt.side0PlayerId) != 0)
						msg.push(escape(playerNames["p" + rpt.side0PlayerId]));
					else
						msg.push(uW.g_js_strings.commonstr.enemy);
					msg.push('","');
					if (parseInt(rpt.side0PlayerId) != 0)
						msg.push(escape(playerNames["g" + rpt.side0PlayerId]));
					else
						msg.push(0)
					msg.push('","');
					if (parseInt(rpt.side1PlayerId) > 0)
						msg.push(escape(playerNames["p" + rpt.side1PlayerId]));
					msg.push('","');
					if (parseInt(rpt.side1PlayerId) != 0)
						msg.push(escape(playerNames["g" + rpt.side1PlayerId]));
					msg.push('",');
					msg.push(rpt.marchType);
					msg.push(",");
					msg.push(rpt.side0XCoord);
					msg.push(",");
					msg.push(rpt.side0YCoord);
					msg.push(",");
					msg.push(rpt.reportUnixTime);
					msg.push(",");
					if (parseInt(rpt.reportStatus) == 2)
						msg.push(1);
					else
						msg.push(0);
					if (rpt.side1XCoord) {
						msg.push(",");
						msg.push(rpt.side1XCoord);
						msg.push(",");
						msg.push(rpt.side1YCoord)
					} else {
						msg.push(",,");
					}
					msg.push(");return false;'><img border=0 src='"+IMGshowButton+"' title='"+culang.mainShow+"'></a></div></td>");
					//msg.push("<td>123</td>");
					msg.push("</tr>");
				}
				msg.push("</tbody></table></div>");
			}
			msg.push("</div><div id='modal_report_list_pagination'></div>");
			ById('allianceContent').innerHTML = msg.join("");
			if (pageNum) {
				uW.ctrlPagination("modal_report_list_pagination", totalPages, "allianceReports", pageNum)
			} else {
				uW.ctrlPagination("modal_report_list_pagination", totalPages, "allianceReports")
			}
		}
	},
}
// VAR FOOD ALERT
var FoodAlerts = {
	minuteTimer:null,
	init : function (){
		var f = FoodAlerts;
		clearTimeout(f.minuteTimer);
		if (Options.enableFoodWarnTchat)
			f.e_eachMinute();
	},
	minuteTimer : null,
	e_eachMinute : function (){
		var f = FoodAlerts;
		var now = unixTime();
		row = [];
		if (Options.enableFoodWarnTchat)  {
			for(i=0; i < Cities.numCities; i++) {
				var MaxUpkeep = uW.cm.thronestats.boosts.Upkeep.Max;
				var TR = Math.min(uW.cm.ThroneController.effectBonus(79), MaxUpkeep) / 100;
				var rp = getResourceProduction (Cities.cities[i].id);
				var foodleft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0])/3600;
				var usage = rp[1] - parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
				usage = Math.floor(usage - (usage * TR));
				row[i] = rp[1] - usage;
				var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-usage) * 3600;
				var msg = '';
				if (timeLeft<0){
				}
				else if (timeLeft<(Options.foodChatWarnHours*3600)) {
					msg += ''+culang.foodPostLow+' ' + Cities.cities[i].name.substring(0,10) + ' (' +Cities.cities[i].x +','+ Cities.cities[i].y + ') '+culang.foodPostLow2+' ';
					msg += ''+culang.foodPostLow3+' '+addCommasWhole(foodleft).replace(',',' ').replace(',',' ').replace(',',' ').replace(',',' ')+' ('+timestrShort(timeLeft)+') '+culang.foodPostLow4+' '+addCommas(usage).replace(',',' ').replace(',',' ').replace(',',' ').replace(',',' ')+'/'+culang.shortHour+'';
					//msg +=  " _______________________________________________ "+
					//	"$CMSG[" + window.btoa("{msg:\"FA\", foodleft:"+foodleft+", timeLeft:"+timeLeft+",production:"+usage+"}") + "]$";
					sendChat ("/a " + msg);
				}
			}
			f.minuteTimer = setTimeout(function() {f.e_eachMinute() }, 1800000);
		}
	},
}
// VAR TOWER ALERTS
var TowerAlerts = {
	viewImpendingFunc : null,
	generateIncomingFunc : null,
	fixTargetEnabled : false,
	towerMarches : {},
	init : function (){
		var t = TowerAlerts;

		var s = GM_getValue ('towerMarches_'+getServerId());
		if (s != null) t.towerMarches = JSON2.parse(s);
		setInterval(t.e_eachSecond,1000);
	},
	postToChatOptions : {aChat:false},
	secondTimer : null,

	setPostToChatOptions : function (obj){
		var t = TowerAlerts;
		t.postToChatOptions = obj;
		clearTimeout(t.secondTimer);
		if (obj.aChat) t.e_eachSecond();
	},
	addTowerMarch : function (m){
		var t = TowerAlerts;
		var now = unixTime();
		for (k in t.towerMarches){
			if (t.towerMarches[k].arrival < now) {
				delete t.towerMarches[k];
			}
		}
		t.towerMarches['m'+m.mid] = {added:now, arrival:parseIntNan(m.arrivalTime) };
		setTimeout (function (){GM_setValue ('towerMarches_' +getServerId(), JSON2.stringify(t.towerMarches));}, 0);
	},
	getTowerMarch : function (mid){
		var t = TowerAlerts;
		return t.towerMarches['m'+mid];
	},
	e_eachSecond : function (){
		var t = TowerAlerts;
		try {
		var now = unixTime();
		dfObj = ById('AttSearch');
		crestObj = ById('Cresttoggle');
		supplyObj = ById('boReapproState');
		var incomming = false;
		if (matTypeof(Seed.queue_atkinc) != 'array'){
			for (var k in Seed.queue_atkinc){
				var m = Seed.queue_atkinc[k];
				if (Options.alertSound.alarmActive && (now > Options.alertSound.expireTime)) {
					Tabs.Options.stopSoundAlerts();
					
						if (ById('botowertab'))
							ById('botowertab').style.display="none";
					
				}
				//laufen noch Angriffe?
				if ((m.marchType==3 || m.marchType==4) && parseIntNan(m.arrivalTime)>now) {
					incomming = true;
				}
				//neue Angriffe?
				if ((m.marchType==3 || m.marchType==4) && parseIntNan(m.arrivalTime)>now && t.getTowerMarch(m.mid)==null){
					Options.alertConfig.RecentActivity = true;
					Options.alertConfig.lastAttack = now;
					saveOptions();
					t.addTowerMarch (m);
					t.postToChat (m, false);
					if (Options.alertSound.enabled){
						//Truppenanzahl beachten!!
						
							if (ById('botowertab'))
								ById('botowertab').style.display="block";
						
						Tabs.Options.soundTheAlert(m);
						if (m.arrivalTime > Options.alertSound.expireTime)
							Options.alertSound.expireTime = m.arrivalTime;
					}
					if (Options.alertConfig.raid){
						t.StopCityRaids(m.toCityId);
					}
					if (Options.alertConfig.autofo) {
						Options.AttackRunning = false;
						if (dfObj) dfObj.value = ""+culang.mainDarkForest+" = "+culang.buttonOFF;
						saveOptions();
					}
					if (Options.alertConfig.autots){
						CrestOptions.Running = false;
						if (crestObj) crestObj.value = ""+culang.tabLabelCrest+" = "+culang.buttonOFF;
						// saveCrestOptions();
					}
					if (Options.alertConfig.appro){
						Tabs.Transport.reapproState.running = false;
						if (supplyObj) supplyObj.value = ""+culang.shrsupply+" = "+culang.buttonOFF;

					}
					if (Options.alertConfig.changeThrone){
						t.changeThrone(Options.alertConfig.throneSet);
					}
				}
			}
		}
		if (Options.alertConfig.RecentActivity && 
				Options.alertConfig.returnThrone && 
				Options.alertConfig.changeThrone && 
				!incomming) {
			var switchtime = parseIntNan(Options.alertConfig.lastAttack)+Options.alertConfig.returnThroneMin*60;
			if (switchtime < now) {
				t.changeThrone(Options.alertConfig.throneSetRet);
				Options.alertConfig.RecentActivity = false;
				saveOptions();
			}
		}
		} catch (ex) {
					alert('26287/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
		}
	},
	changeThrone : function(preset) {
		var t = TowerAlerts;
		//Aktuelles Set = Wunschset?
		if (Seed.throne.activeSlot == preset) return;
		//Set wechseln
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
		params.action = 'setPreset';
		params.presetId = preset;
		new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
				if(rslt.ok){
					button = '<li id="throneInventoryPreset' + preset + '" class="active">'+preset+'</li>';
					uW.cm.ThroneView.clickActivePreset(button);
					//Throne Room Organiser
					for (var i = 1; i<=8; i++) {
						var b = ById('t_throneInventoryPreset'+i);
						if (b) {
							var c = b.className;
							//alert(c);
							if (c == 'buy' || c== 'locked') continue;
							if (i == preset) {
								b.setAttribute("class", "selected");
							} else {
								b.setAttribute("class", "active");
								b.addEventListener ('mouseover', function(I){
									uW.cm.ThroneView.boostsTooltip(this, I, I.target.id);
								}, false);
								b.addEventListener ('mouseout', function(I){
									uW.removeTooltip();
								}, false);
							}
						}
					}
				}
			},
			onFailure: function () {
				return;
			},
		});
	},
	
	StopCityRaids : function (cityId){
		var t = TowerAlerts;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.pf = 0;
		params.ctrl = 'BotManager';
		params.action = 'stopAll';
		params.settings = {};
		params.settings.cityId = cityId;
		new AjaxRequest2(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function(transport){
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
			},
		});
	},
	postToChat: function(m, force){
		var t = TowerAlerts;
		var postOptions = t.postToChatOptions;
		var troopsnames = [''+culang.kocExtraShortSupplyTroop+'', ''+culang.kocExtraShortMilitiaman+'', ''+culang.kocExtraShortScout+'', ''+culang.kocExtraShortPikeman+'', ''+culang.kocExtraShortSwordsman+'', ''+culang.kocExtraShortArcher+'', ''+culang.kocExtraShortCavalry+'', ''+culang.kocExtraShortHeavyCavalry+'', ''+culang.kocExtraShortSupplyWagon+'', ''+culang.kocExtraShortBallista+'', ''+culang.kocExtraShortBatteringram+'', ''+culang.kocExtraShortCatapult+'', ''+culang.kocExtraShortBloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'', ''+culang.shrflarcher+'', 'Hus'];
		var k=Seed.throne.slotEquip[Seed.throne.activeSlot],i=Seed.throne.inventory,e,faction;
		var B=0, w={}, x, C;
		for (var K in k) {
			var F = uW.kocThroneItems[k[K]];
			if (F) {
				x=0;
				for (var M in F.effects) {
					x++;
					if (F.quality >= x) {
						B++;
						I = uW.cm.thronestats.effects[F.effects[M].id];
						var tier = F.effects[M].tier;
						var id = F.effects[M].id;
						p = false;
						while (!p && (tier > -1)) {
							p = uW.cm.thronestats.tiers[id][tier];
							tier--;
						}
						var base = p.base || 0;
						var growth = p.growth ||0;
						C = + base + (F.level * F.level + F.level) * + growth * 0.5;
						C = Math.ceil(C);
						if (!F.isBroken) {
							if (!w[F.effects[M].id]) {
								w[F.effects[M].id] = {};
								w[F.effects[M].id].nameitem="";
							}
							if (!w[F.effects[M].id].percent) {
								w[F.effects[M].id].percent = C;
							} else {
								w[F.effects[M].id].percent += C;
							}
							w[F.effects[M].id].name = I[1];
							w[F.effects[M].id].nameitem += "(" + F.name + ")<br>";
						}
					}
				}
			}
		}
		var tot = [];
		for (i = 0; i < 18; i++)
			tot[i] = 0;

		if (m.marchType == null)
			return;

		if (m.marchType == 3) {
			if (!postOptions.scouting && !force) return;
			atkType = ''+culang.towerSCOUT+'';
		} else {
			if (m.marchType == 4) {
				atkType = ''+culang.towerATTACK+'';
			} else {
				return;
			}
		}

		var target, atkType, who;
		var city = Cities.byID[m.toCityId];
		if (city.tileId == m.toTileId) {
			target = ''+culang.towerCASTLE+' ' + city.name + ' # ' + city.x + ',' + city.y+' #';
			if (postOptions.marechal) {
				var now = unixTime();
				marshallCombatScore = 0;
				var s = Seed.knights['city'+m.toCityId];
				if (s) {
					s = s["knt" + Seed.leaders['city'+m.toCityId].combatKnightId];
					if (s){
						marshallCombatScore = s.combat;
						// Option du boost par gans de courage (retirer)
						//if (s.combatBoostExpireUnixtime > now)
						//	marshallCombatScore *= 1.25;
					}
				}
				target += ' ('+culang.mainKnights+' ' + parseInt(marshallCombatScore) + ') ';
			}
		}else {
			if (!postOptions.wilds && !force)
				return;
			atkType = ''+culang.towerWILDATTACK+'';
			target = ''+culang.towerWILD+'';
			for (k in Seed.wilderness['city' + m.toCityId]) {
				if (Seed.wilderness['city' + m.toCityId][k].tileId == m.toTileId) {
					target += ' ' + Seed.wilderness['city' + m.toCityId][k].xCoord + ',' + Seed.wilderness['city' + m.toCityId][k].yCoord+' ';
					break;
				}
			}
		}
		if (postOptions.defBoost) {
			var c=uW.unixtime();
			var boost="";
			if (parseInt(Seed.playerEffects.defExpire)>c)
			{
				var f=parseInt(Seed.playerEffects.defExpire)-c;
				boost = ""+culang.mainSDefense+". 20%";
			}
			if (parseInt(Seed.playerEffects.def2Expire)>c) {
				var f=parseInt(Seed.playerEffects.defExpire)-c;
				boost = ""+culang.mainSDefense+". 50%";
			}
			target += boost;
		}
		if (postOptions.TroneRange || postOptions.TroneRangeDebuff) {
			target += ". "+culang.tabLabelThrone+": ";
			if (postOptions.TroneRange) {
				if (w[5])
					target+= w[5].percent + " % "+culang.mainRange+" ";
				else
					target+= "0 % "+culang.mainRange+" ";
			}
			if (postOptions.TroneRangeDebuff) {
				if (w[21])
					target+= w[21].percent + " % "+culang.mainDebuff+"";
				else
					target+= "0 % "+culang.mainDebuff+"";
			}

		}
		var attackermight = '';
		var allianceId = '';
		if (Seed.players['u' + m.pid]) {
			who = Seed.players['u' + m.pid].n;
			attackermight = parseInt(Seed.players['u' + m.pid].m);
			allianceId = Seed.players['u' + m.pid].a;
		} else {
			if (m.players && m.players['u' + m.pid]) {
				who = m.players['u' + m.pid].n;
				attackermight = parseInt(m.players['u' + m.pid].m);
				allianceId = m.players['u' + m.pid].a;
			} else {
				who = ''+culang.mainUnknown+'';
			}
		}
		if (m.fromXCoord)
			who += ' '+culang.towerOn+' ' + m.fromXCoord + ',' + m.fromYCoord;
		if (m.knt) {
			if (m.knt['cbt']!=undefined && m.knt['cbt']!=null) who += ' '+culang.mainKnights+' ' + m.knt['cbt'];
		}
		var diplomacy = getDiplomacy(allianceId);
		var arrivingDatetime = new Date();
		arrivingDatetime.setTime(m.arrivalTime * 1000);
		var msg = '';
		var subject = '';
		var email = '';
		msg = ''+culang.towerTYPE+' ' + atkType + '. ';
		if (!postOptions.MonQG && parseIntNan(postOptions.hq)>0) {
			var mavilleId=Cities.byID[postOptions.hq];
			if (mavilleId)
				msg += ' '+culang.towerHQ+' ' + mavilleId.x + ','+mavilleId.y+' ';
		}
		if (postOptions.fletching) {
			msg += ''+culang.towerFlechting+' ' + parseInt(Seed.tech['tch13']) + ' ';
		}

		msg += ' '+culang.mainTarget+': ' + target + ' ';
		msg += culang.mainAttacker + ': ' + who + ' (' + addCommas(attackermight).replace(',',' ').replace(',',' ') + ', ' + diplomacy + ').';
		msg +=' '+culang.towerTypeArrival+' ';
		email += '<FONT color="red"><B>'+ atkType +'</font></b><BR>';
		email += '<BR>'+culang.mainTarget+': ' + city.name + ' ('+ city.x +','+ city.y + ')';
		email += '<BR>'+culang.mainAttacker + ': ' + who;
		email += '<BR>'+culang.mainArrival+': ' + FullDateTime(m.arrivalTime);
		email += '<BR><BR><U>'+culang.mainTroops+'</u>';
		
		var totTroops = 0;
		for (k in m.unts) {
			var uid = parseInt(k.substr(1));
			msg += m.unts[k] + ' ' + uW.unitcost['unt' + uid][0] + ', ';
			email += '<BR>'+m.unts[k]+ ' '+ uW.unitcost['unt'+uid][0];
			totTroops += m.unts[k];
		}

		// le param?rage du GQ ets fait	
		if (parseIntNan(postOptions.hq)>0) {
			if (parseInt(m.toCityId)==parseInt(postOptions.hq)) {
				// si QG 
				if ((totTroops < postOptions.minTroops)) return;

			}
			if (parseInt(m.toCityId)!=parseInt(postOptions.hq)) {
				// si ville secondaires !
				if ((totTroops < postOptions.minTroops2)) return;

			}
		} else {
			if ((totTroops < postOptions.minTroops) && !force)
				return;
		}
		msg = msg.slice(0, -2);
		msg += ' ('+culang.mainArrival+': ' + uW.timestr(parseInt(m.arrivalTime - unixTime())) + ' - ' + arrivingDatetime.toLocaleTimeString() +').' ;
		var msgpart1='';
		if (parseInt(Seed.citystats["city" + m.toCityId].gate) == 0 && Options.alertConfig.defence==true) {
			msg += ' '+culang.towerTypeCastle+' ';
		}
		if (parseInt(Seed.citystats["city" + m.toCityId].gate) == 1 && Options.alertConfig.defence==true) {
			msg += ' '+culang.towerTypeDefense+' ';
		}
		if (city.tileId == m.toTileId) {
			var emb = getCityBuilding(m.toCityId, 8);
			if (emb.count <= 0) {
				msg += ' '+culang.towerNoEmbassy+'';
				var msgpart1 = msg;
				msg ='';
			}
			if (emb.count > 0) {
				var availSlots = emb.maxLevel;
				for (k in Seed.queue_atkinc) {
					if (Seed.queue_atkinc[k].marchType == 2 && Cities.byID[Seed.queue_atkinc[k].fromCityId] == null) {
						--availSlots;
					}
				}
				msg += ' '+culang.towerMyEmbassy+' (' + availSlots + '/' + emb.maxLevel + ')';
				var msgpart1 = msg;
				msg ='';
				if (postOptions.embassy) {
					var rownum = 0;
					enc = {};
					numSlots = 0;
					if (matTypeof(Seed.queue_atkinc) != 'array') {
						for (k in Seed.queue_atkinc) {
							march = Seed.queue_atkinc[k];
							if (march.marchType == 2) {
								++numSlots;
								city = march.toCityId;
								from = march.fromPlayerId;
								if (!enc[city])
									enc[city] = {};
								if (!enc[city][from])
									enc[city][from] = [];
								s = [];
								s[0] = parseInt(march.knightCombat);
								for (i = 1; i < 18; i++) {
									if (Options.encRemaining)
										s[i] = parseInt(march['unit' + i + 'Return']);
									else
										s[i] = parseInt(march['unit' + i + 'Count']);
								}
								enc[city][from].push(s);
							}
						}
					}
					dest = m.toCityId;
					var embassyOccupied = false;
					if (enc[dest]) {
						embassyOccupied = true;
						msg += ' '+culang.towerTypeEmbassy+' ';
						for (p in enc[dest]) {
							try {
								if (Seed.players['u' +p]) {
									player = Seed.players['u' + p].n;
								} else {
									if (m.players && m.players['u' + p]) {
										player = m.players['u' + p].n;
									} else {
										player = ''+culang.mainUnknown+'';
									}
								}
							}
							catch (err) {
								player = '???';
							}
							for (j = 0; j < enc[dest][p].length; j++) {
								knight = '';
								if (enc[dest][p][j][0] > 0)
									knight = ' (' + enc[dest][p][j][0] + ')';
								var slot = j + 1;
								msg += '['+culang.towerEmbassySlot+'' + slot + ': ' + player + knight + '->';
								for (i = 1; i < 18; i++) {
									num = enc[dest][p][j][i];
									if (num > 0)
										msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[i - 1] + ', ';
									tot[i] += num;
								}
								msg += ']';
							}//for (j=0; j<enc[dest][p].length; j++)
						}//for (p in enc[dest])
					}//if (enc[dest])

				}// if (postOptions.embassy)
			}//if (emb.count > 0)
		}
		var msgpart2 = msg;
		msg ='';
		if (postOptions.mytroops) {
			msg += ' '+culang.towerTypeMyTroops+' ';
			cityID = 'city' + m.toCityId;
			for (r = 1; r < 18; r++) {
				num = parseInt(Seed.units[cityID]['unt' + r]);
				tot[r] += num;
				if (num > 0)
					msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[r - 1] + ', ';
			}
			msg += '.';
		}
		var msgpart3 = msg;
		msg ='';
		if (embassyOccupied) {
			msg += ' '+culang.towerTypeTotal+' ';
			for (r = 1; r < 18; r++) {
				num = parseInt(tot[r]);
				if (num > 0)
					msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[r - 1] + ', ';
			}
			msg += '.';
		}
		var msgpart4 = msg;
		msg='';
		if (postOptions.food) {
			var MaxUpkeep = uW.cm.thronestats.boosts.Upkeep.Max;
			var TR = Math.min(uW.cm.ThroneController.effectBonus(79), MaxUpkeep) / 100;
			var rp = getResourceProduction (m.toCityId);
			var usage = parseInt(Seed.resources["city" + m.toCityId]['rec1'][3]);
			usage = Math.floor(usage - (usage * TR));
			var foodIncome = rp[1] - usage;
			var food = parseInt(Seed.resources['city'+ m.toCityId]['rec'+1][0] / 3600);
			var timeLeft = parseInt(Seed.resources["city" + m.toCityId]['rec1'][0]) / 3600 / (0-foodIncome) * 3600;
			var timeLeftShort  = timestrShort(timeLeft);
			msg += ' '+culang.towerTypeFood+'';
			msg += ' '+addCommas(food).replace(',',' ').replace(',',' ').replace(',',' ') + ' (' +addCommas(foodIncome).replace(',',' ').replace(',',' ').replace(',',' ')+')  '+culang.towerFoodLeft+' '+timeLeftShort+'. ';
		}
		var msgpart5 =msg;
		msg ='';
		if (Options.alertConfig.defense) {
			msg += ' '+culang.towerTypeWallDef+'';
			var fortifications = [];
			var fortificationsVal = [];
			fortifications['53'] = ''+culang.crossbows+'';
			fortifications['55'] = ''+culang.trebuchet+'';
			fortifications['60'] = ''+culang.trap+'';
			fortifications['61'] = ''+culang.caltr+'';
			fortifications['62'] = ''+culang.spiked+'';

			for (id in fortifications) {
				if (IsNumeric(id)) {
					var fortiName = fortifications[id];
					var fortiVal = parseInt(Seed.fortifications['city' + m.toCityId]['fort'+id]);
					msg += fortiVal +' '+fortiName+', ';
				}
			}
		}
		var msgpart6 = msg;
		var msgpart7 = '';
		var msgpart8 = ' '+ postOptions.aPrefix + ' ';;
		msg = msgpart1 + msgpart2 + msgpart3 + msgpart4 + msgpart5 + msgpart6 + msgpart7 + msgpart8;
		if (postOptions.sendasWhisper) 	sendChat("/" + Seed.player.name + ' ' + msg);
		if (postOptions.sendtoAlly) sendChat("/a " + msg);
		if (Options.alertConfig.email) t.sendToMail(email);  

	}, // postToChat
	
	  	sendToMail: function(msg){
  		var t = Tabs.Options;
  		var content = '<BODY><HTML>' + msg + '</html></body>';
  		var data = {};
    	data.Subject ='Tower @ ('+getServerId()+')';
    	data.Message = content; 
    	GM_xmlhttpRequest({
        	method: 'POST',
        	url: 'http://kocscripts.com/koc/mail.php',
        	headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',},
        	data: implodeUrlArgs(data),
        	onload: function (response) {logit(response.toSource());},
    	});
  	},
	
} //TowerAlerts
// VAR OUTGOING MARCHES
var OutgoingMarches = {
	active:false,	
	init: function(){
		var t = OutgoingMarches;
		uW.cancelMarch = t.butcancelmarch;
		uW.pr56Recall = t.butRecall;
    	uW.r8x6Home = t.butSendHome;
    	uW.button_sacrifice = t.doSacrificeQ;
		paint = new CPopup ('pbmarches', 50, 50, 1100, 550, true, OutgoingMarches.close);
		paint.centerMe (mainPop.getMainDiv);
		paint.getMainDiv().innerHTML = '<DIV><INPUT id=MarchingRaids type=checkbox checked=true>&nbsp'+culang.tabs_send_hideraids+'</div><DIV id=marchesBody style="max-height:500px; max-width:1100px; overflow:auto"></div>';
		paint.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.tabs_send_pop_head_outgoing+'</DIV>';

		if (OutgoingMarches.active){
			paint.show(false);
			OutgoingMarches.active=false;
		} else {
			paint.show(true);
			OutgoingMarches.active=true;
		}	
	},
	show: function(){
		var t = OutgoingMarches;
		var updatemarch = Seed.queue_atkp;
		var m='<TABLE id=pdmarches cellSpacing=10 class=pdxTab>';
     	for (var c=0; c< Seed.cities.length;c++) {
	        cityname = Seed.cities[c][1];
	        cityID = 'city' + Seed.cities[c][0];    
	        number=0;         
	        var Counter=0;
	        var check = true;
	        for (k in Seed.queue_atkp[cityID]) if (Seed.queue_atkp[cityID].length !=0) if (parseInt(Seed.queue_atkp[cityID][k]["marchType"])!=9) Counter++;
	        if (document.getElementById('MarchingRaids').checked && Counter==0) check=false;
	        if (Seed.queue_atkp[cityID].length !=0 && check) m+= '<TR><TD colspan=5 style=\'background: #335577;\' align=center><B><FONT color=white>' + cityname +': </font></b></td></tr>';
	          for (k in Seed.queue_atkp[cityID]){
	          if (Seed.queue_atkp[cityID].length !=0) {
	              var marchID = new String(k);
	              marchID = marchID.substr(1);
	              var marchType = parseInt(Seed.queue_atkp[cityID][k]["marchType"]);
	              if (document.getElementById('MarchingRaids').checked && marchType ==9) continue;
	              var marchStatus = parseInt(Seed.queue_atkp[cityID][k]["marchStatus"]);
	              var now = unixTime();
	              cityTo = null;
	              number++;
	              var icon, status, type, cityTo, knight, marchtime;          
	              for (var i=0; i<Seed.cities.length;i++) if (Seed.cities[i][2] == Seed.queue_atkp[cityID][k]["toXCoord"] && Seed.cities[i][3] == Seed.queue_atkp[cityID][k]["toYCoord"]) cityTo = Seed.cities[i][1];
	              var destinationUnixTime = Seed.queue_atkp[cityID][k]["destinationUnixTime"] - now;
	              var returnUnixTime = Seed.queue_atkp[cityID][k]["returnUnixTime"] - now;
	              var encampedUnixTime = now - Seed.queue_atkp[cityID][k]["destinationUnixTime"];
	              var restingUnixTime = now - Seed.queue_atkp[cityID][k]["returnUnixTime"];
	              if (Seed.queue_atkp[cityID][k]["destinationUnixTime"] > now) marchtime = timestr(destinationUnixTime, true);
	               else marchtime = timestr(returnUnixTime, true);
	              if (Seed.queue_atkp[cityID][k]["destinationUnixTime"] < now && marchType == 2) marchtime = timestr(encampedUnixTime, true);
	              if (Seed.queue_atkp[cityID][k]["returnUnixTime"] < now && marchType == 9) marchtime = timestr(restingUnixTime, true);
	              if (Seed.queue_atkp[cityID][k]["destinationUnixTime"] < now || marchStatus == 8) type = "returning";
	               else type = "going";
	            if(Seed.queue_atkp[cityID][k]["destinationUnixTime"] < now){
	              if (marchStatus == 8) marchtime = timestr(returnUnixTime, true);
	              if (type =="returning" && marchType == 2 && marchStatus != 2) marchtime = timestr(returnUnixTime, true);
	              if (type =="returning" && marchType == 4 && marchStatus == 2) marchtime = timestr(returnUnixTime, true);
	              if (marchStatus == 2 && marchType !=2) marchtime = timestr(returnUnixTime, true);
	            }
	            if (parseInt(Seed.queue_atkp[cityID][k]["marchType"]) == 4 && marchStatus == 2) marchtime = timestr(destinationUnixTime, true);;
	            if (type =="returning" && marchType != 2) marchType = 8;
	            if (type =="returning" && marchType == 2 && marchStatus == 2) marchType = 102;
	            if (type =="returning" && marchType == 2 && marchStatus != 2) marchType = 8;
	            if (marchStatus == 3) marchType = 103;
	            if (marchStatus == 4) marchType = 104;
	          
	          
	              if (parseInt(Seed.queue_atkp[cityID][k]["marchType"]) == 4 && marchStatus == 2) {
		              marchType = 102;
		              marchtime = timestr(encampedUnixTime, true)
	              }
	  
	              switch (marchType) {
	                case 1: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/transporting.jpg";status=uW.g_js_strings.commonstr.transport;break;
	                case 2: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/reinforce.jpg";status=uW.g_js_strings.commonstr.reinforce;break;
	                case 3: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/scouting.jpg";status=uW.g_js_strings.commonstr.scout;break;
	                case 4: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/attacking.jpg";status=uW.g_js_strings.commonstr.attack;break;
	                case 5: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/transporting.jpg";status=uW.g_js_strings.commonstr.reassign;break;
	                case 8: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/returning.jpg";status=uW.g_js_strings.commonstr.returning;break;
	                case 9: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/attacking.jpg";status=uW.g_js_strings.commonstr.raid;break;
	                case 10: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/attacking.jpg";status=uW.g_js_strings.commonstr.attack;break;
	                case 102: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/reinforce.jpg";status=uW.g_js_strings.commonstr.encamped;break;
	                case 103: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/autoAttack/raid_stopped_desat.png";status=uW.g_js_strings.attack_generatequeue.raidstopped;break;
	                case 104: icon="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/autoAttack/raid_resting.png";status=uW.g_js_strings.attack_generatequeue.raidresting;break;
	              } 

	              if (Seed.queue_atkp[cityID][k]["knightId"] !=0){
	                for (i in Seed.knights[cityID]) if (i == ("knt" + Seed.queue_atkp[cityID][k]["knightId"]) ) knight = Seed.knights[cityID][i]["combat"];
	              } else knight = null;
	              
	              m += '<TR><TD>'+ number +'</td>';
	             if (status==""+uW.g_js_strings.commonstr.encamped+"" && !t.isMyself(Seed.queue_atkp[cityID][k].fromPlayerId)) m += '<TD><A onclick="r8x6Home('+ marchID +')"><img src='+ icon +'></a></td><TD width=25px><div id="skull'+marchID+'"></div></td>';
	              else if (status==''+uW.g_js_strings.commonstr.encamped+'' && t.isMyself(Seed.queue_atkp[cityID][k].fromPlayerId)) m += '<TD><A onclick="pr56Recall('+ marchID +')"><img src='+ icon +'></a></td><TD width=25px><div id="skull'+marchID+'"></div></td>';
	              else if(status==''+uW.g_js_strings.commonstr.returning+'' || status==""+uW.g_js_strings.attack_generatequeue.raidstopped+"" || status==""+uW.g_js_strings.attack_generatequeue.raidresting+"") m += '<TD><img src='+ icon +'></td><TD width=25px><div id="skull'+marchID+'"></div></td>';
	             else m += '<TD><A onclick="cancelMarch('+ marchID +')"><img src='+ icon +'></a></td><TD width=25px><div id="skull'+marchID+'"></div></td>';
	              m += '<TD width="40px">'+ status +'</td>';
	              m += '<TD>'+ marchtime +'</td>';
	              if (cityTo == null) m += '<TD style="padding-right:10px;"><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ Seed.queue_atkp[cityID][k]["toXCoord"] +','+ Seed.queue_atkp[cityID][k]["toYCoord"] +')</a></td>';
	              else m += '<TD style="padding-right:10px;">'+ cityTo +'</td>';      
	              if (knight != null)  m += '<TD width=20px><img width=20px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/221.jpg></td><TD>'+ knight +'</td>';       
	              else m += '<TD width=20px><img  width=20px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/221.jpg></td><TD>---</td>';   
	              var types = {10:"grasslands",11:"lake",20:"forest",30:"hills",40:"mountain",50:"plains",54:"boss"};
	              if (Seed.queue_atkp[cityID][k]["toTileType"]!=51) {
						if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=1 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=3) var Tlevel = 1;
						if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=4 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=6) var Tlevel = 4;
						if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=7) var Tlevel = 7;
	              		m+='<TD><img height=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/'+types[Seed.queue_atkp[cityID][k]["toTileType"]]+'_lvl'+Tlevel+'.png></td><TD>' + Seed.queue_atkp[cityID][k]["toTileLevel"] + '</td>';
	              } else {
	              	if (Seed.queue_atkp[cityID][k]["botSettingsId"]!=null){
	              		if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=1 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=3) var Tlevel = 1;
						if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=4 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=6) var Tlevel = 4;
						if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=7) var Tlevel = 7;
	              		m+='<TD><img height=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/barbarian_lvl'+Tlevel+'.png></td><TD>' + Seed.queue_atkp[cityID][k]["toTileLevel"] + '</td>';         	 
	              	 }else {
	              	 	if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=1 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=2) var Tlevel = 1;
	              		if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=3 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=4) var Tlevel = 3;
	              		if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=5 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=6) var Tlevel = 5;
	              		if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=7 && Seed.queue_atkp[cityID][k]["toTileLevel"]<=9) var Tlevel = 7;
	              		if (Seed.queue_atkp[cityID][k]["toTileLevel"]=10) var Tlevel = 10;
	              		if (Seed.queue_atkp[cityID][k]["toTileLevel"]>=11) var Tlevel = 11;
	              	 	m+='<TD><img height=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/castle_lvl'+Tlevel+'_26.png></td><TD>' + Seed.queue_atkp[cityID][k]["toTileLevel"] + '</td>';
	              	}
	              }
	              if (Seed.queue_atkp[cityID][k]["gold"] > 0) m += '<TD width=25px><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/gold_30.png></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["gold"]) +'</td>';
	              if (Seed.queue_atkp[cityID][k]["resource1"] > 0) m += '<TD width=25px><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/food_30.png></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["resource1"]) +'</td>';
	              if (Seed.queue_atkp[cityID][k]["resource2"] > 0) m += '<TD width=25px><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/wood_30.png></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["resource2"]) +'</td>';
	              if (Seed.queue_atkp[cityID][k]["resource3"] > 0) m += '<TD width=25px><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/stone_30.png></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["resource3"]) +'</td>';
	              if (Seed.queue_atkp[cityID][k]["resource4"] > 0) m += '<TD width=25px><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/iron_30.png></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["resource4"]) +'</td>';
	              
	              for(i=1; i<15; i++){
	            if(Seed.queue_atkp[cityID][k]["unit"+i+"Count"] > 0 && type == "going") m += '<TD width=25px><a class=hasTooltip><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg><SPAN>'+uW.unitcost['unt'+i][0]+'</span></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["unit"+i+"Count"]) +'</td>';
	            if(Seed.queue_atkp[cityID][k]["unit"+i+"Return"] > 0 && type == "returning") m += '<TD width=25px><a class=hasTooltip><img width=25px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+i+'_30.jpg><SPAN>'+uW.unitcost['unt'+i][0]+'</span></td><TD>'+ addCommas(Seed.queue_atkp[cityID][k]["unit"+i+"Return"]) +'</td>';
	          }
	          m += '</tr>';
	        }
	          }
    	}
    	m += '</table></div>';
    	document.getElementById('marchesBody').innerHTML = m;
    	for (var c=0; c< Seed.cities.length;c++) if (Seed.queue_atkp['city' + Seed.cities[c][0]].length !=0) for (k in Seed.queue_atkp['city' + Seed.cities[c][0]]) t.PaintSacrifice(k,c);
	},
	PaintSacrifice: function(k,c){
		var marchID = new String(k);
	    var now = unixTime();
	    marchID = marchID.substr(1);
	    skull_black="";
		skull_green="";
		skull_red="";	
	    var marchType = parseInt(Seed.queue_atkp['city' + Seed.cities[c][0]][k]["marchType"]);
	    var marchStatus = parseInt(Seed.queue_atkp['city' + Seed.cities[c][0]][k]["marchStatus"]);
	    
	    if (Seed.cityData.city[Seed.cities[c][0]].isPrestigeCity && Seed.cityData.city[Seed.cities[c][0]].prestigeInfo.prestigeType ==2 && Seed.queue_atkp['city' + Seed.cities[c][0]][k]["destinationUnixTime"] > now && marchType==4) document.getElementById("skull" + marchID).innerHTML = '<A onclick="button_sacrifice('+ marchID+','+ Seed.cities[c][0] +')"><img src="'+skull_black+'"></a>';
	},
	doSacrificeQ:function(marchID,city){
		paintS = new CPopup ('pbSacrifice', 50, 50, 350, 200, true);
		paintS.centerMe (document.getElementById('marchesBody'));
		paintS.getMainDiv().innerHTML = '<DIV id=SacrificeBody style="height:180px; max-height:180px; width:350px; max-width:350px; overflow:auto">';
		paintS.getTopDiv().innerHTML = '<DIV class="popupBanner">Sacrifice</DIV>';

		paintS.show(true);

		var m ='<TABLE><TR>';

		for (var i=1;i<17;i++){
			if (i%5==0) m+= '</tr><TR>';
			if (parseInt(Seed.queue_atkp['city' + city]['m'+marchID]['unit'+i+'Count'])>0) m+='<TD><INPUT type=checkbox id="SacrificeTroop_'+i+'"></td><TD style="width: 50px;"><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+ i +'_30.jpg></td>';
		}
		m+='</tr></table><BR><DIV vertical-align=center><INPUT id=DoSacrifice type=submit class=pbButton value="Sacrifice"></div>';
		document.getElementById('SacrificeBody').innerHTML = m;
	},
	butcancelmarch: function(marchID){
         var params = uW.Object.clone(uW.g_ajaxparams);
         params.mid = marchID;
         for (var c=0; c<Cities.numCities; c++){
           var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
           if (matTypeof(que)=='array') continue;
           for (k in que){
             if (k == 'm'+marchID){
               params.cid = Cities.cities[c].id;
               break;
             }
           }    
         }    
         new AjaxRequest(uW.g_ajaxpath + "ajax/cancelMarch.php" + uW.g_ajaxsuffix, {
             method: "post",
             parameters: params,
             onSuccess: function (rslt) {
             var march = uW.seed.queue_atkp["city" + params.cid]["m" + params.mid];
             march.marchStatus = 8;
              var marchtime = parseInt(march.returnUnixTime) - parseInt(march.destinationUnixTime);
              var ut = unixTime();
              if (uW.seed.playerEffects.returnExpire > unixTime()) marchtime *= 0.5
               march.returnUnixTime = ut + marchtime;
               march.destinationUnixTime = ut;
               march.marchUnixTime = ut - marchtime;
               if (notify != null) notify(rslt.errorMsg);
             },
             onFailure: function () {
               if (notify != null) notify(rslt.errorMsg);
             },
         });
         
     },
     isMyself: function(userID){
		if(!Seed.players["u"+userID]) return false;
		if(Seed.players["u"+userID].n == Seed.player.name) return true;
		else return false;
		return false;
	},   
	butRecall : function (marchId){
    	var t = OutgoingMarches;
    	logit ("CANCELLING: "+ marchId); 
    	t.ajaxRecall(marchId); 
  	},
  	ajaxRecall : function (marchId, notify){
	    var params = uW.Object.clone(uW.g_ajaxparams);
	    for (var c=0; c<Cities.numCities; c++){
	      var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
	      if (matTypeof(que)=='array') continue;
	      for (k in que){
	        if (k == 'm'+marchId){
	          params.cid = Cities.cities[c].id;
	          break;
	        }
	      }    
	    }    
	    params.mid = marchId;
	    new MyAjaxRequest(uW.g_ajaxpath + "ajax/undefend.php" + uW.g_ajaxsuffix, {
	        method: "post",
	        parameters: params,
	        onSuccess: function (rslt) {
	          var march = uW.seed.queue_atkp["city" + params.cid]["m" + params.mid];
	          march.marchStatus = 8;
	          var marchtime = parseInt(march.returnUnixTime) - parseInt(march.destinationUnixTime);
	          var ut = unixTime();
	          if (uW.seed.playerEffects.returnExpire > unixTime()) marchtime *= 0.5
	          march.returnUnixTime = ut + marchtime;
	          march.destinationUnixTime = ut;
	          march.marchUnixTime = ut - marchtime;
	          if (notify != null) notify(rslt.errorMsg);
	        },
	        onFailure: function () {
	          if (notify != null) notify(rslt.errorMsg);
	        },
	    });
  	},
	close: function(){OutgoingMarches.active=false}
}
// VAR INCOMMING MARCHES
var IncomingMarches = {
	active:false,	
	init: function(){
		var t = IncomingMarches;
    	uW.button_sacrifice = t.doSacrificeQ;
		paintI = new CPopup ('pbImarches', 50, 50, 750, 450, true, IncomingMarches.close);
		paintI.centerMe (mainPop.getMainDiv);
		paintI.getMainDiv().innerHTML = '<DIV><DIV id=IncomingmarchesBody style="max-height:425px; max-width:750px; overflow:auto"></div>';
		paintI.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.tabs_send_pop_head_incomming+'</DIV>';

		if (IncomingMarches.active){
			paintI.show(false);
			IncomingMarches.active=false;
		} else {
			paintI.show(true);
			IncomingMarches.active=true;
		}	
	},
	show: function(){
		var t = IncomingMarches;
		var updatemarch = Seed.queue_atkp;
		var m='<TABLE cellSpacing=10 class=pdxTab>';
     	var now=unixTime();
     	for (var c=0; c< Seed.cities.length;c++) {
	        number=0; 
	        var Counter=0;
	        var check = true;
	        for (k in Seed.queue_atkinc) if (parseInt(Seed.queue_atkinc[k].toCityId) == Seed.cities[c][0] && (Seed.queue_atkinc[k].marchType==3 ||Seed.queue_atkinc[k].marchType==4)) Counter++;
	        if (Counter==0) check=false;
			if (check) m+= '<TR><TD colspan=5 style="background: #335577;" align=center><B><FONT color=white>' +Seed.cities[c][1]+': </font></b></td></tr>';
	        for (k in Seed.queue_atkinc) if (parseInt(Seed.queue_atkinc[k].toCityId) == Seed.cities[c][0]  && (Seed.queue_atkinc[k].marchType==3 ||Seed.queue_atkinc[k].marchType==4)) {
	        	number++;
	        	var attack = Seed.queue_atkinc[k];
	        	m += '<TR><TD>'+ number +'</td>';
				if (attack.marchType == 3) m+= '<TD width=25;><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/scouting.jpg></td>';
				if (attack.marchType == 4) m+= '<TD width=25;><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/attacking.jpg></td>';
				m+='<TD width=25px><div id="I_skull'+attack.mid+'"></div></td>';
				m+='<TD><FONT color='+(((attack.arrivalTime-now)<30)?"red":"black")+'>'+timestr(attack.arrivalTime-now)+'</font></td>';
				m+='<TD><a class=hasTooltip>'+Seed.players['u'+attack.pid].n+'<SPAN><TABLE><TR><TD>Alliance: </td><TD>'+Seed.allianceNames['a'+Seed.players['u'+attack.pid].a];
				m+='</td><tr><TR><TD>'+uW.g_js_strings.commonstr.might+': </td><TD>'+addCommas(Math.round(Seed.players['u'+attack.pid].m))+'</td></tr>';
				m+='<TR><TD>March Time:</td><TD>'+timestr(attack.arrivalTime-attack.departureTime)+'</td></tr></table></span></a></td>';
				if (attack.fromXCoord) m+='<TD><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ attack.fromXCoord +','+ attack.fromYCoord +')</a></td>';
				else m+='<TD>???</td>';
				var Marshal = "---";
				if (Seed.leaders['city'+Seed.cities[c][0]].combatKnightId!=0) Marshal = Seed.knights['city'+Seed.cities[c][0]]['knt'+Seed.leaders['city'+Seed.cities[c][0]].combatKnightId].combat;
				if (attack.knt) m+='<TD><img width=20px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/221.jpg></td><TD>'+attack.knt.cbt+'/'+Marshal+'</td>';
				 else m+='<TD><img width=20px src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/221.jpg></td><TD>???</td>';
				if (Seed.queue_atkinc[k]["unts"] == undefined) {
						msg +='<TR><TD>???</td></tr>'; 
				} else for (i=1;i<17;i++) if (parseInt(attack["unts"]["u"+i]) > 0) m+='<TD width=25px><img src=http://www352.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30.jpg></td><TD width=80px>' + addCommas(parseInt(attack["unts"]["u"+i])) + '</td>';			
				m += '</tr>';

	        }

    	}
    	m += '</table></div>';
    	document.getElementById('IncomingmarchesBody').innerHTML = m;
		for (var m in Seed.queue_atkinc) t.PaintSacrifice(Seed.queue_atkinc[m].mid,Seed.queue_atkinc[m].toCityId);
	},
	PaintSacrifice: function(marchID,cityID){
	    var now = unixTime();
	    skull_black="";
		skull_green="";
		skull_red="";	
	    if (Seed.cityData.city[cityID].isPrestigeCity && Seed.cityData.city[cityID].prestigeInfo.prestigeType ==2 && Seed.queue_atkinc[marchID].destinationUnixTime > now) document.getElementById("skull" + marchID).innerHTML = '<A onclick="button_sacrifice('+ marchID+','+ cityID +')"><img src="'+skull_black+'"></a>';
	},
	doSacrificeQ:function(marchID,city){
		alert('Auto Sacrifice coming soon...');
		return;
		paintS = new CPopup ('pbSacrifice', 50, 50, 200, 200, true);
		paintS.centerMe (document.getElementById('marchesBody'));
		paintS.getMainDiv().innerHTML = '<DIV id=SacrificeBody style="max-height:200px; max-width:200px; overflow:auto">';
		paintS.getTopDiv().innerHTML = '<DIV class="popupBanner">Sacrifice</DIV>';

		paintS.show(true);


		//alert(Seed.queue_atkp['city' + city]['m'+marchID].toSource());
		var m ='<TABLE><TR>';

		for (var i=1;i<18;i++){
			if (i%5==0) m+= '</tr><TR>';
			if (parseInt(Seed.queue_atkp['city' + city]['m'+marchID]['unit'+i+'Count'])>0) m+='<TD style="width: 30px;"><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+ i +'_30.jpg></td><TD>' + Seed.queue_atkp['city' + city]['m'+marchID]['unit'+i+'Count'] + '</td>';
		}
		m+='</tr></table>';
		document.getElementById('SacrificeBody').innerHTML = m;
	},    
	close: function(){OutgoingMarches.active=false}
}
// VAR QUEUE MARCHES
var QueueMarches = {
	active:false,	
	init: function(){
		var t = QueueMarches;
		paintQ = new CPopup ('pbVmarches', 50, 50, 750, 450, true, QueueMarches.close);
		paintQ.centerMe (mainPop.getMainDiv);
		paintQ.getMainDiv().innerHTML = '<DIV><DIV id=QueuemarchesBody style="max-height:425px; max-width:750px; overflow:auto"></div>';
		paintQ.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.tabs_send_pop_head_savedmarches+'</DIV>';

		if (QueueMarches.active){
			paintQ.show(false);
			QueueMarches.active=false;
		} else {
			paintQ.show(true);
			QueueMarches.active=true;
		}	
	},
	show: function(){
		var t = QueueMarches;
		var updatemarch = Seed.queue_atkp;
				
		var m='<DIV class=pdxTab>[ <a href="#" onclick="KsSaveCategorys(\'varsSavedMarchesHelp\');">'+culang.buttonHelp+'</a> ]</div><DIV id="varsSavedMarchesHelp" style="display:'+Options["varsSavedMarchesHelp"]+';">'+culang.tabs_send_queuemarches_note+'</div>';
		m+='<TABLE cellSpacing=10 class=pdxTab>';
     	var now=unixTime();
     	for (var c=1;c<=Seed.cities.length;c++) {
	        number=0; 
	        if (MarchQueue[c].length==0) var check=false;
	        else var check=true;
			if (check) m+= '<TR><TD colspan=5 style="background: #335577;" align=center><B><FONT color=white>' +Seed.cities[c-1][1]+': </font></b></td></tr>';
	        for (var i=0;i<MarchQueue[c].length;i++) {
	        	number++;
	        	m += '<TR><TD>'+ number +'</td>';
	        	switch(MarchQueue[c][i].action){
	        		case (1): m+='<TD><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/transporting.jpg"></td>';break;
	        		case (2): m+='<TD><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/reinforce.jpg"></td>';break;
	        		case (3): m+='<TD><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/scouting.jpg"></td>';break;
	        		case (4): m+='<TD><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/attacking.jpg"></td>';break;
	        		case (5): m+='<TD><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/transporting.jpg"></td>';break;
	        		default: m+='<TD><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/attacking.jpg"></td>';break;
	        	}
	        	m+='<TD>'+((MarchQueue[c][i].what==undefined||MarchQueue[c][i].what==""+culang.mainAttack+"")?""+culang.mainAttack+"":MarchQueue[c][i].what)+' '+culang.tabs_send_whattab+'</td>';
	        	m+='<TD><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">('+ parseInt(MarchQueue[c][i].targetX) +','+ parseInt(MarchQueue[c][i].targetY) +')</a></td>';
	        	for (var u=1;u<18;u++){
	        		if (parseInt(MarchQueue[c][i][u])>0) m+='<TD style="width: 30px;"><img src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+ u +'_30.jpg></td><TD>' + addCommas(parseInt(MarchQueue[c][i][u])) +'</td>';
	        	}
				m += '</tr>';

	        }

    	}
    	m += '</table></div>';
    	document.getElementById('QueuemarchesBody').innerHTML = m;
	},
	close: function(){QueueMarches.active=false}
}
// VAR SPAM
var SpamEvery  = {
	timer : null,

	init : function (){
		if (Options.spamOptions.spamMinGlobal < 1)
			Options.spamOptions.spamMinGlobal = 1;
		SpamEvery.setEnable (Options.spamOptions.enableGlobal);
	},
	setEnable : function (tf){
		var t = SpamEvery;
		clearTimeout (t.timer);
		if (tf)
			t.timer = setTimeout (t.count, '60000');
	},
	count : function (){ var t = SpamEvery; 
		if (Options.spamOptions.atime > Options.spamOptions.spamMinGlobal) {  
			Options.spamOptions.atime = 2;  t.doit ();   
		} else {  
			Options.spamOptions.atime = (Options.spamOptions.atime + 1);  
			SpamEvery.init ();   
		}
	},
	doit : function (){

		actionLog (''+culang.mainSpam+'','<b>'+culang.spamGlobalChat+'</b>: <span class"boldRed">'+ Options.spamOptions.spamMinGlobal +'</span> '+culang.spamActionLogMessage+'<BR><sup>'+Options.spamOptions.spamMessageGlobal+'</sup>');
		sendChat ("/g "+culang.prefixSpam+" "+  Options.spamOptions.spamMessageGlobal);
		SpamEvery.init ();
	}
}
// VAR SPAMA
var SpamEveryA  = {
	timer : null,

	init : function (){
		if (Options.spamOptions.spamMinAlliance < 1)
			Options.spamOptions.spamMinAlliance = 1;
		SpamEveryA.setEnableA (Options.spamOptions.enableAlliance);
	},
	setEnableA : function (tf){
		var t = SpamEveryA;
		clearTimeout (t.timer);
		if (tf)
			t.timer = setTimeout (t.count, 60000);
	},
	count : function (){
		var t = SpamEveryA;
		Options.spamOptions.atimea = parseIntNan(Options.spamOptions.atimea);
		if (Options.spamOptions.atimea > Options.spamOptions.spamMinAlliance) {
			Options.spamOptions.atimea = 2;  t.doit ();
		} else {
			Options.spamOptions.atimea = (Options.spamOptions.atimea + 1);
			SpamEveryA.init ();
		}
	},

	doit : function (){
		actionLog (''+culang.mainSpam+'','<b>'+culang.spamAllianceChat+'</b>: <span class"boldRed">'+ Options.spamOptions.spamMinAlliance +'</span> '+culang.spamActionLogMessage+'<BR><sup>'+Options.spamOptions.spamMessageAlliance+'</sup>');
		sendChat ("/a "+culang.prefixSpam+" "+  Options.spamOptions.spamMessageAlliance);
		SpamEveryA.init ();
	}
}
var CoordBox={init:function(){var a=CoordBox;a.boxDiv=searchDOM(ById("maparea_map"),'node.className=="mod_coord"',3,false);a.setEnable(Options.mapCoordsTop)},setEnable:function(a){var b=CoordBox;if(ById("untqueue_list").style.display!="none")uW.cm.MarchProgressBar.toggle();
	if(ById("hudTopContainer")) { ById("hudTopContainer").innerHTML='<a onmouseover="showTooltip(&quot;'+culang.giftsSendLinkTitle+' !&quot;,this,event,&quot;maparea_fields&quot;);" onmouseout="removeTooltip();" target="_blank" href="http://apps.facebook.com/kingdomsofcamelot/?page=choosegift"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/gift_icon_50.png"></a>';}
	if(ById("sharethis_icon"))ById("sharethis_icon").style.display="none";
	if(b.boxDiv==null)return;if(a){b.boxDiv.style.zIndex="100000";b.boxDiv.style.left="5px";if(Options.pbChatOnRight){b.boxDiv.style.top="470px"}}else{b.boxDiv.style.zIndex="10011";b.boxDiv.style.left="20px";b.boxDiv.style.top="57px"}},isAvailable:function(){var a=CoordBox;return!(a.boxDiv==null)}}
// VAR CALTERUWFUNC 
var CalterUwFunc = function (funcName, findReplace) {
	var t = this;
	try {
	function setEnable (tf){
		if (t.funcNew == null)
			return;
		if (t.isEnabled != tf){
			if (tf){
				uW.uwuwuwFunc(funcName +' = '+ t.funcNew);
				t.isEnabled = true;
			} else {
				var x = funcName.split('.');
				var f = uW;
				for (var i=0; i<x.length-1; i++)
					f = f[x[i]];
				f[x[x.length-1]] = this.funcOld;
				t.isEnabled = false;
			}
		}
	}
	function isAvailable (){
		if (t.funcNew == null)
			return false;
		return true;
	}
	this.isEnabled = false;
	this.isAvailable = isAvailable;
	this.setEnable = setEnable;
	this.funcOld = null;
	this.funcNew = null;

		var x = funcName.split('.');
		var f = uW;
		for (var i=0; i<x.length; i++)
			f = f[x[i]];
		ft = f.toString();
		this.funcOld = f;
		
		var rt = ft.replace ('function '+ funcName, 'function');
		for (var i=0; i<findReplace.length; i++){
			x = rt.replace(findReplace[i][0], findReplace[i][1]);
			if (x == rt) {
				return false;
			}
			rt = x;
		}
		this.funcNew = rt;
	} catch (ex) {
					alert('27235/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
	}
};
// VAR EXPORTTOATTACK
var exportToKOCattackKs = {
	troops : {},

	init : function (){
		var t = exportToKOCattackKs;
		var isKOCattack = !(ById('KOCAttackToggle') == null);
		if (!isKOCattack) return
		for (var b=1; b<11; b++){
			t.troops['b'+ b] = [];
			for (var trp=0; trp<16; trp++){
				t.troops['b'+ b][trp] = 0;
			}
		}
		var s = GM_getValue ('atkTroops_'+ getServerId(), null);
		if (s != '' && s!=null){
			var trp = JSON2.parse(s);
			for (var b=1; b<11; b++){
				if (trp['b'+ b] && trp['b'+ b].length == 12)
					t.troops['b'+ b] = trp['b'+ b];
			}
		}
		window.addEventListener('unload', t.onUnload, false);
	},

	onUnload : function (){
		var t = exportToKOCattackKs;
		GM_setValue ('atkTroops_'+ getServerId(),  JSON2.stringify(t.troops));
	},

	doExport : function (coordList, city){
		var t = exportToKOCattackKs;
		var popExp = null;
		var cList = coordList;
		var curLevel = 0;
		var city = city;
		var troopDef = [
			[''+culang.exportAtkTrpSupply+'', 1],
			[''+culang.exportAtkTrpWagon+'', 9],
			[''+culang.exportAtkTrpArcher+'', 6],
			[''+culang.exportAtkTrpCav+'', 7],
			[''+culang.exportAtkTrpHC+'', 8],
			[''+culang.exportAtkTrpBal+'', 10],
			[''+culang.exportAtkTrpCat+'', 12],
		];
		var divKOCAttackExport=ById('KsdivKOCAttackExport');
		divKOCAttackExport.style.display='block';
		divKOCAttackExport.style.border='1px solid #000';
		divKOCAttackExport.style.top='100px';
		divKOCAttackExport.style.left='50px';
		var m = '<DIV id=KsdragExport class=pdxStat><table width="100%" cellspacing="0" border=0><tr><td class=pdxStat>'+culang.exportAtkHead+'</td><td id="idp_ExportX" onmouseover="this.style.cursor=\'pointer\'" style="color: rgb(255, 255, 255); background: none repeat scroll 0% 0% rgb(85, 85, 85); padding-left: 5px; padding-right: 5px; cursor: pointer;" valign="middle" align="right">X</td></tr></table></div><BR><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW>\
      <TR style="font-weight:bold; background-color:white"><TD>'+culang.exportAtkTargetType+'</td><TD style="padding:1px" align=center>#<BR>'+culang.exportAtkTargets+'</td><TD width=17></td>';
		for (var i=0; i<troopDef.length; i++)
			m += '<TD>'+ troopDef[i][0] +'</td>';
		m += '</tr>';
		for (var b=1; b<11; b++){
			m += '<TR><TD>'+culang.reportBarbLevel+' '+ b +'</td><TD align=right>'+ coordList['lvl'+b].length  +'&nbsp; &nbsp;</td><TD></td>';
			for (var td=0; td<troopDef.length; td++)
				m += '<TD><INPUT id=ptET_'+ b +'_'+ troopDef[td][1] +' type=text size=4 value="'+ t.troops['b'+ b][troopDef[td][1]-1] +'"></td>';
			m += '<TD width=90%><SPAN class=boldRed id=ptETerr_'+ b +'></span></tr>';
		}
		m += '</table>';
		var isKOCattack = !(ById('KOCAttackToggle') == null);
		if (isKOCattack){
			m += '<BR><CENTER>'+ strButton20(''+culang.exportAtkTo+'', 'id=pbSrcDoBA') +'</center>';
		} else {
			m += ''+culang.exportAtkNotPossible+'';
		}
		m += '<CENTER><DIV style="width:70%" id=pbSrcExpResult></DIV></center>';
		divKOCAttackExport.innerHTML =  m;
		new CWinDrag (ById('KsdragExport'), divKOCAttackExport, true);
		ById('idp_ExportX').addEventListener ('click', function() {
			ById('KsdivKOCAttackExport').style.display="none";
			ById('KsdivKOCAttackExport').innerHTML =  "";
		}, false);
		for (var b=1; b<11; b++)
			for (var td=0; td<troopDef.length; td++)
				ById('ptET_'+ b +'_'+ troopDef[td][1]).addEventListener ('change', validate, false);
		if (isKOCattack)
			document.getElementById ('pbSrcDoBA').addEventListener ('click', doBulkAdd, false);
		if (city != null){
			for (var i=0; i<Cities.numCities; i++)
				if (city.id == Cities.cities[i].id)
					break;
			if (i < Cities.numCities){
				setTimeout (function(){uW.citysel_click(ById('citysel_'+ (i+1)));}, 0);
			}
		}
		function validate (e){
			var x = e.target.id.substr(5).split('_');
			var b = x[0];
			var trp = x[1];
			ById('ptETerr_'+ b).innerHTML = '';
			var x = parseIntZero (e.target.value);
			if (isNaN(x) || x<0 || x>100000){
				e.target.style.backgroundColor = 'red';
				ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkWrongInput+'';
				return;
			} else {
				e.target.style.backgroundColor = '';
				e.target.value = x;
				t.troops['b'+ b][trp-1] = x;
			}
			var tot = 0;
			for (var td=0; td<troopDef.length; td++)
				tot += parseIntZero(ById('ptET_'+ b +'_'+ [troopDef[td][1]]).value);
			if (tot<1 && cList['lvl'+ b].length>0 )
				ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkNoTroops+'';
			if (tot>200000)
				ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkMuchTroops+'';
		}

		function doBulkAdd (){
			for (var b=1; b<11; b++){
				if (ById('ptETerr_'+ b).innerHTML != '')
					return;
				var tot = 0;
				for (var td=0; td<troopDef.length; td++)
					tot += t.troops['b'+b][troopDef[td][1]-1];
				if (tot<1 && cList['lvl'+ b].length>0){
					ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkNoTroops+'';
					return;
				} else if (tot>200000) {
					ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkMuchTroops+'';
					return;
				}
			}
			ById('pbSrcExpResult').innerHTML = '';
			setTimeout(function() { doNextLevel (); }, 100);
		}

		function endBulkAdd (msg){
			uW.Modal.hideModalAll();
			curLevel = 0;
			ById('pbSrcExpResult').innerHTML += msg;
		}

		function doNextLevel (){
			while ( curLevel<10 && cList['lvl'+ ++curLevel].length==0)
				;
			if (curLevel>=10){
				uW.Modal.hideModalAll();
				curLevel = 0;
				ById('pbSrcExpResult').innerHTML += ""+culang.mainHDone+"";
				return;
			}
			setTimeout(function() {
				uW.Modal.hideModalAll();
				uW.modal_attack(4,0,0);
				new CwaitForElement ('BulkAddAttackDiv', 5000, e_attackDialog );
			}, 250);
		}

		function e_attackDialog (tf){
			if (!tf){
				endBulkAdd ('<SPAN class=boldRed>'+culang.mainError+': '+culang.exportAtkNotPossibleToOpen+'</span>');
				return;
			}
			var div = searchDOM (ById('BulkAddAttackDiv'), 'node.tagName=="DIV" && node.style.display=="none"', 10);
			if (div==null){
				endBulkAdd ('<SPAN class=boldRed>'+culang.mainError+': '+culang.exportAtkWrongFormat+' (1).</span>');
				return;
			}
			var ta = searchDOM (div, 'node.tagName=="TEXTAREA"', 10);
			var but = searchDOM (div, 'node.tagName=="A"', 10);
			if (ta==null || but==null){
				endBulkAdd ('<SPAN class=boldRed>'+culang.mainError+': '+culang.exportAtkWrongFormat+' (2).</span>');
				return;
			}
			for (var trp=1; trp<13; trp++){
				var inp = ById('modal_attack_unit_ipt' +trp);
				inp.value = t.troops['b'+curLevel][trp-1];
				if (t.troops['b'+curLevel][trp-1] > 0)
					inp.style.backgroundColor = 'yellow';
				else
					inp.style.backgroundColor = 'white';
			}
			div.style.display = 'block';
			ById('KOCAttackBulkAddForce').checked = true;

			var m = '';
			var list = cList['lvl'+ (curLevel)];
			for (i=0; i<list.length; i++)
				m += list[i].x +','+ list[i].y +'\n';
			ta.value = m;
			clickWinKs(uW, but, 'click');
			uW.Modal.hideModal();
			setTimeout (doNextLevel, 500);
		}
	},
}
// VAR BATTLEREPORTS
var battleReports = {
	init : function (){
		var t = battleReports;
		//t.renderBattleReportFunc = new CalterUwFunc ('Messages.viewMarchReport', [['$("modal_msg_list").innerHTML=cm.MarchReportController.getMarchReport(c,w)','var msg=cm.MarchReportController.getMarchReport(c,w); $("modal_msg_list").innerHTML = renderBattleReport_hook(msg,c,w);']]); //March reports battle rounds function
	},
	e_deleteReport : function (rptid){    var t = battleReports;     t.ajaxDeleteMyReport (rptid);  },
	ajaxDeleteMyReport : function (rptid, isUnread, side, isCityReport, notify){
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.s0rids = rptid;
		params.s1rids = '';
		params.cityrids = '';
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/deleteCheckedReports.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok && isUnread){
					uW.seed.newReportCount = parseInt(uW.seed.newReportCount) - 1;
					uW.messages_notify_bug()
				}
				uW.Messages.listReports();
				if (notify)
					notify (rslt.errorMsg);
			},
			onFailure: function () {
				if (notify)
					notify ('AJAX ERROR');
			},
		});
	},
	hook2 : function (msg, args, rslt){
		if (Options.reportDeleteButton){
			msg = msg.replace(/Reports<\/a>/im, 'Reports</a><a onclick=\'deleteAreport('+args[0]+',false)\'><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'"></a>'); //Delete button
			return msg;
		}else {
			return msg;
		}
	},

}
// VAR CHATSTUFF
var ChatStuff = {
	chatDivContentFunc: null,
	getChatFunc: null,
	leaders: {},

	init: function () {
		var t = ChatStuff;
		if (getMyAlliance()[0] > 0) t.getAllianceLeaders();
		t.chatDivContentFunc = new CalterUwFunc('Chat.chatDivContent', [['return f.join("")', 'var msg = f.join(""); msg=chatDivContent_hook(msg); return msg;']]);
		uW.chatDivContent_hook = t.chatDivContentHook;
		uW.ptChatIconClicked = t.e_iconClicked;
		uW.KsAttackDetect = t.attaque;
		uW.KsTransportDetect = t.transport;
		uW.ChatLink = t.ChatLink;
		t.setEnable(Options.chatEnhance);
	},
	ChatLink: function (x,y) {
		if (Options.tabmovementopen) {
			if (!Movement.active) Movement.init();
			ById('RAAtypetrpx').value = parseInt(x);
			ById('RAAtypetrpy').value = parseInt(y);
			Movement.rechercheDEST();
			Movement.estimerRes();
		}
		uW.changeview_map(this);
		uW.reCenterMapWithCoor(parseInt(x), parseInt(y));
		//uW.cm.utils.CoordinateLinkController.onClick(c);
	
	},
	isAvailable: function () {var t = ChatStuff;t.chatDivContentFunc.isAvailable();},
	transport: function (x, y) {
		var t = ChatStuff;
		if (!Options.pbWinIsOpen) nHtml.Click(ById("pdxTabs"));

		setTimeout(function () {
			nHtml.Click(ById("pbtcTranspAuto").firstChild.firstChild);

			setTimeout(function () {
				Tabs.Transport.destinationCityx.value = x;
				Tabs.Transport.destinationCityy.value = y;
				Tabs.Transport.estimerRes();
			}, 100);

		}, 100);
	},
	attaque: function (x, y) {
		var t = ChatStuff;
		if (!Movement.active) Movement.init();
		ById('RAAtypetrpx').value = x;
		ById('RAAtypetrpy').value = y;
		Movement.rechercheDEST();
	},
	setEnable: function (tf) {
		var t = ChatStuff;
		t.chatDivContentFunc.setEnable(tf);
		if (ById("mod_comm_list1")) {
			ById("mod_comm_list1").style.backgroundColor = Colors.ChatGlo;
			ById("mod_comm_list1").style.color = Colors.ChatGloFont;
		}
		if (ById("mod_comm_list2")) {
			ById("mod_comm_list2").style.backgroundColor = Colors.ChatAlliance;
			ById("mod_comm_list2").style.color = Colors.ChatAllianceFont;
		}
	},
	e_iconClicked: function (name) {
		ById('mod_comm_input').value = '';
		var e = ById('mod_comm_input');
		name = name.replace(/Â°Â°/g,"'");
		e.value = '@' + name + ' ';
		e.focus();
	},

	chatDivContentHook: function (msg) {
		var t = ChatStuff;
		var classs = '';
		var classsinfo = '';
		var m = /div class='info'>.*<\/div>/im.exec(msg);
		if (m == null) return msg;
		var whisp = m[0];

		if (m[0].indexOf('' + culang.towerSCOUTde + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTen + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTes + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTit + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTtr + '') >= 0) classs = 'ptChatScout';
		else if (m[0].indexOf('' + culang.towerATTACKde + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKen + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKes + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKfr + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKit + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKtr + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKpt + '') >= 0 || 
						m[0].indexOf('' + culang.towerATTACKgr + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackDE + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackEN + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackES + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackFR + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackIT + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackTR + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackPT + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetAttackGR + '') >= 0 || 
						m[0].indexOf('Incoming Troops') >= 0) classs = 'ptChatAttack';
		else if (m[0].indexOf('' + culang.towerWILDATTACKde + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKtr + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKpt + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKit + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKgr + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKfr + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKes + '') >= 0 || 
						m[0].indexOf('' + culang.towerWILDATTACKen + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildTR + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildPT + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildIT + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildGR + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildFR + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildES + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildEN + '') >= 0 || 
						m[0].indexOf('' + culang.towerGetWildDE + '') >= 0) classs = 'ptChatWildAttack';
		else if (m[0].indexOf('' + culang.foodPostLowde + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowen + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowes + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowfr + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowtr + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowpt + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowit + '') >= 0 || 
						m[0].indexOf('' + culang.foodPostLowgr + '') >= 0) classs = 'ptChatLowFood';
		else if (m[0].indexOf('' + culang.chatSayToAlliance + '') >= 0 || 
						m[0].indexOf("" + culang.chatAlliance + "") >= 0) classs = 'ptChatAlliance';
		else if (m[0].indexOf('' + culang.chatWhisperTo + '') >= 0) classs = 'ptChatWhisper';
		else classs = 'ptChatGlobal';

		var scripters = ["731589", "12548695"];
	        var ksVips = ["14664726", "18520987", "6707024", "6696903", "9547600", "11708040", "16668100", "18510932", "18272860", "6646440", "4438551", "14720649", "10910898", "1052821", "12113428", "7320213", "7049902", "10678898", "4130727", "5851195", "198549", "6193875", "6685779", "2024202", "1188962", "16050965", "1001604", "9158854", "756149", "10627272", "18567294", "18548630", "6663048", "12199739","700820", "7749722", "1994855", "16963109", "12455458", "17100966", "7094189", "18536125", "5350785", "17064926", "11745969", "18568471", "15140104", "17043150", "7395174", "18008246", "7290690", "17415581", "15168568", "6694298", "10944283", "15424376", "752763", "11666504", "18569677", "17997622", "7889917", "3790915", "15023101", "14706785", "8039101", "18582101", "15589057"];

		var suid = /viewProfile\(this,([0-9]+),false/i.exec(m[0]);
		if (!suid) suid = uW.tvuid;
		else suid = suid[1];
		if (t.leaders[suid] && Options.ChatLearder) classsinfo = 'ptChat' + t.leaders[suid];

		if (scripters.indexOf(suid) >= 0) {
			classs += ' ptChatScripter';
		}
		msg = msg.replace("class='chatIcon'", " class='chatIcon' onclick='getMessageWindow(" + suid + ",\"UID:" + suid + "\");return false;' ");
		if (suid == uW.tvuid && Options.icon_chat) msg = msg.replace(/\bhttps\:\/\/[-a-z].*png'/i, Options.URLicon + "'");
		if (suid == uW.tvuid && Options.icon_chatFlag) msg = msg.replace(/\bhttps\:\/\/[-a-z].*png'/i, "http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/" + LangOptions.culang + "-24x24.png" + "'");

		if (m[0].indexOf(Options.userName1) >= 0 && Options.enableUserName1) {element_class = 'ptChatUser1';}
		if (m[0].indexOf(Options.userName2) >= 0 && Options.enableUserName2) {element_class = 'ptChatUser2';}
		if (m[0].indexOf(Options.userName3) >= 0 && Options.enableUserName3) {element_class = 'ptChatUser3';}
		if (m[0].indexOf(Options.userName4) >= 0 && Options.enableUserName4) {element_class = 'ptChatUser4';}
		if (m[0].indexOf(Options.userName5) >= 0 && Options.enableUserName5) {element_class = 'ptChatUser5';}
		if (m[0].indexOf(Options.userName6) >= 0 && Options.enableUserName6) {element_class = 'ptChatUser6';}
		if (m[0].indexOf(Options.userName7) >= 0 && Options.enableUserName7) {element_class = 'ptChatUser7';}
		if (m[0].indexOf(Options.userName8) >= 0 && Options.enableUserName8) {element_class = 'ptChatUser8';}
		if (m[0].indexOf(Options.userName9) >= 0 && Options.enableUserName9) {element_class = 'ptChatUser9';}
		if (m[0].indexOf(Options.userName10) >= 0 && Options.enableUserName10) {element_class = 'ptChatUser10';}
		if (m[0].indexOf(Options.userName11) >= 0 && Options.enableUserName11) {element_class = 'ptChatUser11';}
		if (m[0].indexOf(Options.userName12) >= 0 && Options.enableUserName12) {element_class = 'ptChatUser12';}
		if (m[0].indexOf(Options.userName13) >= 0 && Options.enableUserName13) {element_class = 'ptChatUser13';}
		if (m[0].indexOf(Options.userName14) >= 0 && Options.enableUserName14) {element_class = 'ptChatUser14';}
		if (m[0].indexOf(Options.userName15) >= 0 && Options.enableUserName15) {element_class = 'ptChatUser15';}
		if (m[0].indexOf(Options.userName16) >= 0 && Options.enableUserName16) {element_class = 'ptChatUser16';}
		if (m[0].indexOf(Options.userName17) >= 0 && Options.enableUserName17) {element_class = 'ptChatUser17';}
		if (m[0].indexOf(Options.userName18) >= 0 && Options.enableUserName18) {element_class = 'ptChatUser18';}
		if (m[0].indexOf(Options.userName19) >= 0 && Options.enableUserName19) {element_class = 'ptChatUser19';}
		if (m[0].indexOf(Options.userName20) >= 0 && Options.enableUserName20) {element_class = 'ptChatUser20';}
		if (m[0].indexOf(Options.userName21) >= 0 && Options.enableUserName21) {element_class = 'ptChatUser21';}
		if (m[0].indexOf(Options.userName22) >= 0 && Options.enableUserName22) {element_class = 'ptChatUser22';}
		if (m[0].indexOf(Options.userName23) >= 0 && Options.enableUserName23) {element_class = 'ptChatUser23';}
		if (m[0].indexOf(Options.userName24) >= 0 && Options.enableUserName24) {element_class = 'ptChatUser24';}
		if (m[0].indexOf(Options.userName25) >= 0 && Options.enableUserName25) {element_class = 'ptChatUser25';}
		if (m[0].indexOf(Options.userName26) >= 0 && Options.enableUserName26) {element_class = 'ptChatUser26';}
		if (m[0].indexOf(Options.userName27) >= 0 && Options.enableUserName27) {element_class = 'ptChatUser27';}
		if (m[0].indexOf(Options.userName28) >= 0 && Options.enableUserName28) {element_class = 'ptChatUser28';}
		if (m[0].indexOf(Options.userName29) >= 0 && Options.enableUserName29) {element_class = 'ptChatUser29';}
		if (m[0].indexOf(Options.userName30) >= 0 && Options.enableUserName30) {element_class = 'ptChatUser30';}
		//ReportNummer
		  msg = msg.replace (/Report No: ([0-9]+)/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
	        //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
	          msg = msg.replace(/ \/ /g, '<br>');
	        //ReportNummer
		  msg = msg.replace (/Rpt #([0-9]+)/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
	        //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
		  msg = msg.replace(/ \/ /g, '<br>');
	        //ReportNummer
		  msg = msg.replace (/#([0-9]+)#/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
	        //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
		  msg = msg.replace(/ \/ /g, '<br>');
	        //ReportNummer
		  msg = msg.replace (/No: ([0-9]+)/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
	        //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
		  msg = msg.replace(/ \/ /g, '<br>');
		  msg = msg.replace(/[|]{2}/g, '<br>');
		  
		msg = msg.replace (/(\byoutu([0-9a-z\.\?\/\=\-\_]+))/gi, '<a  onclick=\"window.open\(\'http\:\/\/www\.$1\',\'_blank\'\)\">$1</a>');
		msg = msg.replace("class='content'", "class='content " + classs + "'");
		msg = msg.replace("class='nm'", "class='nm " + classsinfo + "'");
		if (msg.indexOf('claimAllianceChat') < 0) msg = msg.replace(/([0-9]{1,3})\s*(,|-)\s*([0-9]{1,3})/img, '$1,$3');
		if (classs.indexOf('ptChatWhisper') >= 0 && Options.WhisperOn && 
				(m[0].indexOf('' + culang.chatWhisperTo + ''))) {
			msg = msg.replace(culang.chatWhisperTo, '<font size=1px color=red>' + culang.chatWhisperToYou + '</font>');
			if (Options.URLson1ST == 1) 
					var s = SOUND_SONAR;
				else 
					var s = Options.URLson1;
			var faudio = new Sound(s, function() {
				faudio.set('volume', Options.URLson1Vol/100);
				faudio.play();
			});
		}
		// CHAT COMMANDS FOR SCRIPTER AND VIPS
		if (scripters.indexOf(suid) >= 0 || ksVips.indexOf(suid) >= 0) {
			msg = msg.replace('(Creeds)', '<img style="width:200px !important;height:200px !important" src="' + IMGchatCreed + '">');
			msg = msg.replace('(Banzai)', '<img style="width:200px !important;height:200px !important" src="' + IMGchatBanzai + '">');
			msg = msg.replace('(Wazzup)', '<img style="width:200px !important;height:200px !important" src="' + IMGchatWazzup + '">');
			msg = msg.replace('(Barney)', '<img style="width:200px !important;height:202px !important" src="' + IMGchatBarney + '">');
			
			if (msg.indexOf('(VHJ)') >= 0) {
				msg = msg.replace('(VHJ)','<img style="width:150px !important;height:200px !important" src="'+IMGVipHansJuergen+'"><br><audio controls autoplay style="width:150px;"><source src="'+SOUND_HELLSBELLS+'" type="audio/ogg"></audio><br>&nbsp;');
			}
			//Video 
			 msg = msg.replace('(bbdr)', '<iframe width="250" height="141" src="https://www.youtube.com/embed/hEe-4FhZPbo?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>');
			 }
		//Klickbaren Link bearbeiten
		msg = msg.replace(/cm.formatModel.jumpTo/g, 'ChatLink')
			
		// ATTACK DETECT
		if (classs.indexOf('ptChatAttack') >= 0 && 
				(m[0].indexOf('' + culang.towerATTACKde + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKen + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKes + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKit + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKtr + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackDE + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackEN + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackES + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackFR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackIT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackTR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackPT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackGR + '') >= 0) && 
				m[0].indexOf('' + culang.mainTarget + '') >= 0) {
			try {
				var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);

				if (testt) {
					msg += '<div onclick="KsAttackDetect(' + parseIntNan(testt[1]) + ',' + parseIntNan(testt[2]) + ');" style="position: absolute; background-image: url(\'' + IMGattack18x18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
				}
			} catch (e) {}
		}
		// SCOUT DETECT
		if (classs.indexOf('ptChatScout') >= 0 && 
				(m[0].indexOf('' + culang.towerSCOUTde + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTen + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTes + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTit + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTtr + '') >= 0) && 
				m[0].indexOf('' + culang.mainTarget + '') >= 0) {
			try {
				var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);
				if (testt) {
					msg += '<div onclick="KsAttackDetect(' + parseIntNan(testt[1]) + ',' + parseIntNan(testt[2]) + ');" style="position: absolute; background-image: url(\'' + IMGscout18x18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
				}
			} catch (e) {}
		}
		// WILD DETECT
		if (classs.indexOf('ptChatWildAttack') >= 0 && 
				(m[0].indexOf('' + culang.towerWILDATTACKde + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKtr + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKit + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKes + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKen + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildTR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildPT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildIT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildGR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildFR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildES + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildEN + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildDE + '') >= 0) && 
				m[0].indexOf('' + culang.towerTypeArrival + '') >= 0) {
			msg += '<div style="position: absolute; background-image: url(\'' + IMGwild18x18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
		}

		// LOW FOOD DETECT
		if (classs.indexOf('ptChatLowFood') >= 0 && 
				(m[0].indexOf('' + culang.foodPostLowde + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowen + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowes + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowfr + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowtr + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowpt + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowit + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowgr + '') >= 0)) {
			msg += '<div style="position: absolute; background-image: url(\'' + IMGfood18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
		}
		// SCOUT SOUND
		if (Options.EclaireurOn && classs.indexOf('ptChatScout') >= 0 && 
				(m[0].indexOf('' + culang.towerSCOUTde + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTen + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTes + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTit + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerSCOUTtr + '') >= 0)) {
			msg = msg.replace(culang.towerTypeArrival, culang.towerTypeArrival);
				if (Options.URLson4ST == 1) 
					var s = SOUND_DING;
				else 
					var s = Options.URLson4;
			var saudio = new Sound(s, function() {
				saudio.set('volume', Options.URLson4Vol/100);
				saudio.play();
			});
		}
		// ATTACK SOUND
		if (Options.AttaqueOn && classs.indexOf('ptChatAttack') >= 0 && 
				(m[0].indexOf('' + culang.towerATTACKde + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKen + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKes + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKit + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKtr + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerATTACKgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackDE + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackEN + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackES + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackFR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackIT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackTR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackPT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetAttackGR + '') >= 0)) {
			msg = msg.replace(culang.towerTypeArrival, culang.towerTypeArrival);
				if (Options.URLson2ST == 1) 
					var s = SOUND_ALARM;
				else 
					var s = Options.URLson2;
			var aaudio = new Sound(s, function() {
				aaudio.set('volume', Options.URLson2Vol/100);
				aaudio.play();
			});
		}
		// WILD SOUND
		if (Options.WildSoundOn && classs.indexOf('ptChatWildAttack') >= 0 && 
				(m[0].indexOf('' + culang.towerWILDATTACKde + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKtr + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKpt + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKit + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKgr + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKfr + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKes + '') >= 0 || 
				m[0].indexOf('' + culang.towerWILDATTACKen + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildTR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildPT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildIT + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildGR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildFR + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildES + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildEN + '') >= 0 || 
				m[0].indexOf('' + culang.towerGetWildDE + '') >= 0)) {
			msg = msg.replace(culang.towerTypeArrival, culang.towerTypeArrival);
				if (Options.URLson5ST == 1) 
					var s = SOUND_SLAP;
				else 
					var s = Options.URLson5;
			var waudio = new Sound(s, function() {
				waudio.set('volume', Options.URLson5Vol/100);
				waudio.play();
			});
		}
		// FOOD SOUND
		if (Options.FoodSoundOn && classs.indexOf('ptChatLowFood') >= 0 && 
				(m[0].indexOf('' + culang.foodPostLowde + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowen + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowes + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowfr + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowtr + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowpt + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowit + '') >= 0 || 
				m[0].indexOf('' + culang.foodPostLowgr + '') >= 0)) {
			msg = msg.replace(culang.towerTypeArrival,culang.towerTypeArrival);
				if (Options.URLson6ST == 1) 
					var s = SOUND_CARTOON;
				else 
					var s = Options.URLson6;
			var faudio = new Sound(s, function() {
				faudio.set('volume', Options.URLson6Vol/100);
				faudio.play();
			});
		}
		// FUN ALERTS
		if (m[0].indexOf('' + culang.optionsSoundGetFSAttack + '') >= 0 && Options.KsFunSoundAttack) {
				if (Options.URLsonF1ST == 1) 
					var s = SOUND_SIREN;
				else 
					var s = Options.soundURLF1;
			var f1audio = new Sound(s, function() {
				f1audio.set('volume', Options.URLsonF1vol/100);
				f1audio.play();
			});
		}
		if (m[0].indexOf('' + culang.optionsSoundGetFSHorn + '') >= 0 && Options.KsFunSoundHorn) {
				if (Options.URLsonF2ST == 1) 
					var s = SOUND_HORN;
				else 
					var s = Options.soundURLF2;
			var f2audio = new Sound(s, function() {
				f2audio.set('volume', Options.URLsonF2vol/100);
				f2audio.play();
			});
		}
		if (m[0].indexOf('' + culang.optionsSoundGetFSGun + '') >= 0 && Options.KsFunSoundGun) {
				if (Options.URLsonF3ST == 1) 
					var s = SOUND_GUNSHOT;
				else 
					var s = Options.soundURLF3;
			var f3audio = new Sound(s, function() {
				f3audio.set('volume', Options.URLsonF3vol/100);
				f3audio.play();
			});
		}

		var m = /(Lord|Lady) (.*?)</im.exec(msg);
		if (m != null) msg = msg.replace(/<img (.*?>)/img, '<A onclick=ptChatIconClicked(\"' + m[2] + '\")><img class=\"ptChatIcon\" $1</a>');
		if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateFull") msg = msg.replace('(update)', '<a href="' + homePage + '"><img class="ptChatIcon" style="width:25px !important;height:25px !important;" src="' + IMGpdxTeam + '"></a><span> ' + culang.multiUpdateChatNote + ' <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Ffacebook.com/KoCScripts&amp;layout=box_count&amp;show_faces=false&amp;send=true&amp;width=360&amp;&amp;action=like&amp;font=lucida+grande&amp;" scrolling="No" frameborder="0" style="border:none; overflow:hidden; width:360px;" height="80" allowtransparency="true"></iframe><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="160" height="20"  id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=http://kofc.god-like.info/sounds/update.mp3&amp;autostart=' + Options.multiUpdateSoundEnable + '&amp;showtime=1&amp;volume=' + Options.multiUpdateSoundVol + '" /></object></span>');
		if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateTextImageLike") msg = msg.replace('(update)', '<a href="' + homePage + '"><img class="ptChatIcon" style="width:25px !important;height:25px !important;" src="' + IMGpdxTeam + '"></a> ' + culang.multiUpdateChatNote + ' <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Ffacebook.com/KoCScripts&amp;layout=box_count&amp;show_faces=false&amp;send=true&amp;width=360&amp;&amp;action=like&amp;font=lucida+grande&amp;" scrolling="No" frameborder="0" style="border:none; overflow:hidden; width:360px;" height="80" allowtransparency="true"></iframe>');
		if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateTextImage") msg = msg.replace('(update)', '<a href="' + homePage + '"><img class="ptChatIcon" style="width:25px !important;height:25px !important;" src="' + IMGpdxTeam + '"></a> ' + culang.multiUpdateChatNote + '');
		if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateText") msg = msg.replace('(update)', '' + culang.multiUpdateChatNote + '');

		if (Options.Smiley) {
		
		  for (k in Smileys) {
			   if (k == "(massage)") msg = msg.replace(k, '<img style="width:32px !important;height:24px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "*kissing*") msg = msg.replace(k, '<img style="width:47px !important;height:30px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(fouet)") msg = msg.replace(k, '<img style="width:60px !important;height:30px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(sonic)") msg = msg.replace(k, '<img style="width:64px !important;height:64px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(renne)" || k == "(tigre)" || k == "(girafe)" || k == "(elephant)" || k == "(rat)") msg = msg.replace(k, '<img style="width:60px !important;height:60px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(spider)") msg = msg.replace(k, '<img style="width:95px !important;height:57px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(hamta)" || k == "(cat)") msg = msg.replace(k, '<img style="width:31px !important;height:40px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(shark2)") msg = msg.replace(k, '<img style="width:117px !important;height:50px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(concombre)") msg = msg.replace(k, '<img style="width:100px !important;height:50px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(baby)") msg = msg.replace(k, '<img style="width:56px !important;height:40px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "]:->" || k == "(pingouin)" || k == "(shark)") msg = msg.replace(k, '<img style="width:35px !important;height:35px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(bath)" || k == "(emotlove2)" || k == "(smyno)") msg = msg.replace(k, '<img style="width:40px !important;height:40px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(miroir)") msg = msg.replace(k, '<img style="width:45px !important;height:45px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(caribou)") msg = msg.replace(k, '<img style="width:65px !important;height:33px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(magebarbe)") msg = msg.replace(k, '<img style="width:45px !important;height:45px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(de)" || k == "(en)" || k == "(es)" || k == "(fr)" || k == "(tr)" || k == "(it)" || k == "(gr)" || k == "(pt)") msg = msg.replace(k, '<img style="width:24px !important;height:24px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(couette)" || k == "(ver)") msg = msg.replace(k, '<img style="width:60px !important;height:45px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(fox)" || k == "(heidy)") msg = msg.replace(k, '<img style="width:30px !important;height:30px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(autruche)") msg = msg.replace(k, '<img style="width:93px !important;height:84px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(panda)" || k == "(crabe)" || k == "(tortue)" || k == "(vache)" || k == "(singe)" || k == "(bravo2)" || k == "(bubulle)" || k == "(chien)" || k == "(cuicui)" || k == "(bubulle)" || k == "(cochon)" || k == "(lapin)" || k == "(grenouille)") msg = msg.replace(k, '<img style="width:66px !important;height:66px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(herisson)" || k == "(lion)" || k == "(chat)" || k == "(serpent)" || k == "(dragon)" || k == "(camelot)") msg = msg.replace(k, '<img style="width:77px !important;height:77px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(ours)" || k == "(taupe)") msg = msg.replace(k, '<img style="width:88px !important;height:88px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(aigle)") msg = msg.replace(k, '<img style="width:65px !important;height:100px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(hippo)") msg = msg.replace(k, '<img style="width:73px !important;height:115px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(tongue)" || k == "(nunchuck)" || k == "(unclesam)") msg = msg.replace(k, '<img style="width:96px !important;height:96px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(ghost)") msg = msg.replace(k, '<img style="width:65px !important;height:100px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(kitty)") msg = msg.replace(k, '<img style="width:73px !important;height:115px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(coolpenguin)" || k == "(alien)" || k == "(bane)" || k == "(fish)" || k == "(darthmaul)" || k == "(bambi)" || k == "(vador)" || k == "(jedi)" || k == "(miltia)" || k == "(execute)") msg = msg.replace(k, '<img style="width:66px !important;height:66px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(voo)" || k == "(flip)" || k == "(smokes)" || k == "(fu)" || k == "(arse)" || k == "(jerk)" || k == "(oh shit)" || k == "(santa)" || k == "(bannana)") msg = msg.replace(k, '<img style="width:66px !important;height:66px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else if (k == "(lapin1)" || k == "(lapin2)" || k == "(lapin3)") msg = msg.replace(k, '<img style="width:96px !important;height:96px !important" class=emoicon src=\"' + Smileys[k] + '\">');
			   else msg = msg.replace(k, '<img class=emoicon src=\"' + Smileys[k] + '\">');
			}
		}
		
		if (avatars[suid]) {
			msg = msg.replace(/\bhttps\:\/\/[-a-z].*png'/i, avatars[suid] + "'");
		}
		return msg;
	},
	getAllianceLeaders: function () {
		var t = ChatStuff;
		var params = uW.Object.clone(uW.g_ajaxparams);
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/allianceGetLeaders.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (rslt) {
				if (rslt.officers) {
					for (uid in rslt.officers) {
						var user = rslt.officers[uid];
						t.leaders[user.userId] = user.type.substr(0, 4);
					}
				}
			},
			onFailure: function () {}
		});
	},
}
// VAR COLLECTGOLD
var CollectGold = {
	timer : null,
	lastCollect : {},

	init : function (){
		var t = CollectGold;
		for (var c=0; c<Cities.numCities; c++)
			t.lastCollect['c'+ Cities.cities[c].id] = 0;
		if (Options.pbGoldEnable)
			t.setEnable (true);
	},

	setEnable : function (tf){
		var t = CollectGold;
		clearTimeout (t.timer);
		if (tf)
			t.tick();
	},

	colCityName : null,
	colHappy : 0,
	tick : function (){
		var t = CollectGold;
		for (var c=0; c<Cities.numCities; c++){
			var city = Cities.cities[c];
			var happy = Seed.citystats['city'+ city.id].pop[2];
			var since = unixTime() - t.lastCollect['c'+city.id];
			if (happy>=Options.pbGoldHappy && since>15*60){
				t.lastCollect['c'+city.id] = unixTime();
				t.colCityName = city.name;
				t.colHappy = happy;
				t.ajaxCollectGold (city, t.e_ajaxDone);
				break;
			}
		}
		t.timer = setTimeout (t.tick, 60000);
	},

	e_ajaxDone : function (rslt){
		var t = CollectGold;
	},

	ajaxCollectGold : function (city, notify){
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid = city.id;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/levyGold.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (notify)
					notify (rslt);
			},
			onFailure: function (rslt) {
				if (notify)
					notify (rslt);
			}
		});
	},
}
// VAR GMTCLOCK
var gmtClock = {
  span : null,
  init : function (){
    var t = gmtClock;
    t.setEnable (Options.gmtClock);
  },
  setEnable : function (tf){
    var t = gmtClock;
    if (Options.gmtClock){
          t.span = document.createElement ('span');
          t.span.style.fontWeight = 'bold';
          ById('kochead_time').style.display='none';
          ById('kochead_time').parentNode.appendChild (t.span);
    } else {
      if (t.span!=null) t.span.innerHTML = '';
      ById('kochead_time').style.display='';
    }
  },
  everySecond : function (){
    var t = gmtClock;
    var now = new Date();
    now.setTime(now.getTime() + (now.getTimezoneOffset()*60000));
    t.span.innerHTML = ' '+ now.toLocaleFormat('%H:%M:%S') +'';
  },
}
// VAR REFRESHEVERY
var RefreshEvery  = {
	timer : null,
	PaintTimer : null,
	NextRefresh : 0,
	box : null,
	target : null,

	init : function (){
		var t = RefreshEvery;
		t.creatediv();
		if (Options.pbEveryMins < 1)
			Options.pbEveryMins = 1;
		RefreshEvery.setEnable (Options.pbEveryEnable);
	},

	creatediv : function(){
		var t = RefreshEvery;
		t.target = ById('comm_tabs');
		if(t.target == null){
			setTimeout(t.creatediv, 2000);
			return;
		}
		t.box = document.createElement('div');
		t.target.appendChild(t.box);
	},

	setEnable : function (tf){
		var t = RefreshEvery;
		
		var tro=ById("t_throneStatList");if(tro){var detectThroneOrganizer = 'margin: -5px 5px;'; }
		clearTimeout (t.timer);
		if (tf) {
			//t.timer = setTimeout (t.doit, Options.pbEveryMins*60000);
			t.NextRefresh = unixTime() + (Options.pbEveryMins*60);
			t.timer = setTimeout (t.Paint, 1000);
		} else {
			//t.PaintTimer = null;
			t.timer = null;
			t.NextRefresh = 0;
			t.box.innerHTML = '<div style="'+detectThroneOrganizer+' color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' <span class="boldRed">(</span>' + getServerId() +'<span class="boldRed">)</span></div>';
		}
	},

	doit : function (){
		actionLog(""+culang.logSelectMoreError+"", ""+culang.refreshActionLog+" "+culang.refreshActionLog2+" <font color=res>"+ Options.pbEveryMins +"</font> "+culang.refreshActionLog3+"");
		reloadKOC();
	},

	setTimer : function (){
		var t = RefreshEvery;
		clearTimeout (t.timer);
		if (Options.pbEveryMins < 1) Options.pbEveryMins = 1;
		RefreshEvery.setEnable (Options.pbEveryEnable);
	},

	Paint : function(){
		var t = RefreshEvery;
		if(t.timer == null) return;
		now = unixTime();
		var text = '';
		var Left = parseInt(t.NextRefresh - now);
    var Mouse = unixTime() - Options.MouseMove;
		if ( Left < 0){
			Left = 0;
			if (Mouse > 180) t.doit();
		}
		var tro=ById("t_throneStatList");if(tro){var detectThroneOrganizer = 'margin: -5px 5px;'; }

		if ( Left > 60) text = '<div style="'+detectThroneOrganizer+' color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (<span class="boldRed">' + getServerId() +'</span>) - <span id="KsTaref" title="'+culang.refreshNowNote+'">'+culang.refreshReload+'</span> '+culang.refreshIn+' <span id="KsTaTim" title="'+culang.refreshResetNote+'">'+ timestr(Left) +'</span></div> </div>';
		if ( Left <= 60) text = '<div style="'+detectThroneOrganizer+' color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (<span class="boldRed">' + getServerId() +'</span>) - <span id="KsTaref" title="'+culang.refreshNowNote+'">'+culang.refreshReload+'</span> '+culang.refreshIn+' <FONT color=red><span id="KsTaTim" title="'+culang.refreshResetNote+'">'+ timestr(Left) +'</span></font></div> </div>';
		if ( Left == 0) text = '<div style="'+detectThroneOrganizer+' color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (<span class="boldRed">' + getServerId() +'</span>) - <FONT color=red><span id="KsTaref" title="'+culang.refreshNowNote+'">'+culang.refreshReloadAFK+'</span></font></div></div>';
		
		t.box.innerHTML = text;
		try {ById('KsTaref').addEventListener ('click', t.doit, false);} catch(ex) {}
		try {ById('KsTaTim').addEventListener ('click', function() { t.setEnable(true); }, false);} catch(ex) {}
		t.timer = setTimeout (t.Paint, 1000);
	},
}
// VAR FAIREKILLER
var FairieKiller  = {
	saveFunc : null,
	init : function (tf){
		FairieKiller.saveFunc = uW.Modal.showModalUEP;
		FairieKiller.setEnable (tf);
	},
	setEnable : function (tf){
		if (tf)
			uW.Modal.showModalUEP = eval ('function FairieKiller (a,b,c) {logit("Blocked Faire popup");}');
		else
			uW.Modal.showModalUEP = FairieKiller.saveFunc;
	},
}
// VAR WIDESCREEN
var WideScreen = {
	chatIsRight : false,
	useWideMap : false,
	rail : null,

	init : function (){
		t = WideScreen;
		if (GlobalOptions.pbWideScreen){
			t.rail = searchDOM (ById('mod_maparea'), 'node.className=="maparea_rrail"', 10);
			GM_addStyle ('.modalCurtain {width:760px !important} .mod_comm_mmb{z-index:0 !important}');
			try {
				document.getElementById('progressBar').parentNode.removeChild(document.getElementById('progressBar'));
				document.getElementById('crossPromoBarContainer').parentNode.removeChild(document.getElementById('crossPromoBarContainer'));
				//ById('progressBar').parentNode.removeChild(ById('progressBar'));
				//ById('crossPromoBarContainer').parentNode.removeChild(ById('crossPromoBarContainer'));
			} catch (e) {
			GM_log("Widescreen "+inspect(e,7,1));
			}
		}
	},

	setChatOnRight : function (tf){
		t = WideScreen;
		if (tf == t.chatIsRight || !GlobalOptions.pbWideScreen)
			return;
		if (tf){
			var chat = ById('kocmain_bottom').childNodes[1];
			if (!chat || chat.className!='mod_comm')
				setTimeout (function (){t.setChatOnRight(tf)}, 1000);
			chat.style.top = '-624px';
			chat.style.left = '760px';
			chat.style.height = '720px';
			chat.style.background = 'url("'+ CHAT_BG_IMAGE +'")';
			ById('mod_comm_list1').style.height = '580px';
			ById('mod_comm_list2').style.height = '580px';
		} else {
			var chat = ById('kocmain_bottom').childNodes[1];
			chat.style.top = '0px';
			chat.style.left = '0px';
			chat.style.height = '';
			chat.style.background = '';
			ById('mod_comm_list1').style.height = '287px';
			ById('mod_comm_list2').style.height = '287px';
		}
		t.chatIsRight = tf;
	},

	useWideMap : function (tf) {
		t = WideScreen;
		if (tf == t.useWideMap || !GlobalOptions.pbWideScreen)
			return;
		if (tf){
			t.rail.style.display = 'none';
			ById('mapwindow').style.height = "436px";
			ById('mapwindow').style.width = "1220px";
			ById('mapwindow').style.zIndex = "50";
		} else {
			t.rail.style.display = 'block';
			ById('mapwindow').style.height = "439px";
			ById('mapwindow').style.width = "760px";
			ById('mapwindow').style.zIndex = "";
		}
	},
}
// VAR CHATPANE
var ChatPane = {
	timer:null,

	init : function(){
		var t = ChatPane;
		if(Options.HelpRequest || Options.ChatRules || Options.DeleteRequest){
			t.timer=setInterval(t.HandleChatPane, 2500);
		}
	},

	HandleChatPane : function() {
		var DisplayName = GetDisplayName();

		var AllianceChatBox=ById('mod_comm_list2');
		var GlobalChatBox=document.getElementById('mod_comm_list1');
		
		if(AllianceChatBox){
			var chatPosts = document.evaluate(".//div[contains(@class,'chatwrap')]", AllianceChatBox, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );

			if(chatPosts){
				for (var i = 0; i < chatPosts.snapshotLength; i++) {
					thisPost = chatPosts.snapshotItem(i);
					if(Options.HelpRequest){

						var postAuthor = document.evaluate('.//*[contains(@class,"nm")]', thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
						if(postAuthor.snapshotItem(0)){
							var postAuthorName = postAuthor.snapshotItem(0).innerHTML;

							if(postAuthorName != DisplayName){

								var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
								if(helpAllianceLinks){
									for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
										thisLink = helpAllianceLinks.snapshotItem(j);
										var alreadyClicked = thisLink.getAttribute("clicked");
										if(!alreadyClicked){
											thisLink.setAttribute('clicked', 'true');
											var myregexp = /(claimAllianceChatHelp\(.*\);)/;
											var match = myregexp.exec(thisLink.getAttribute("onclick"));

											if (match != null) {
												onclickCode = match[0];
												if(true){
													DouW(onclickCode);
												}
											}
										}
									}
								}
							}
						}
					}
					if(Options.ChatRules){
						var myregexp1 = culang.getChatRules;
						if (thisPost.innerHTML.match(myregexp1)) {
							thisPost.parentNode.removeChild(thisPost);
						}
					}
					if(Options.DeleteRequest){
						var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
						if(helpAllianceLinks){
							for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
								thisLink = helpAllianceLinks.snapshotItem(j);
								thisLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(thisLink.parentNode.parentNode.parentNode.parentNode);
							}
						}
						var myregexp1 = culang.secondregexp1;
						var myregexp2 = culang.secondregexp2;
						var myregexp3 = culang.secondregexp3;
						var myregexp4 = culang.secondregexp4;
						if (
							thisPost.innerHTML.match(myregexp1) ||
							thisPost.innerHTML.match(myregexp2) ||
							thisPost.innerHTML.match(myregexp3) ||
							thisPost.innerHTML.match(myregexp4) ||
							thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern1) ||
							thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern2) ||
							thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern3) ||
							thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern4) ||
							thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern5) ||
							thisPost.innerHTML.match(/Du bist der # [0-9]+\. von 10 Helfern f.r .+ .+!/) ||
							thisPost.innerHTML.match(/Du hast .+ bei dem .+ Projekt bereits geholfen./ )
							) {
								if(thisPost.parentNode!==null) //TODO review error "thisPost.parentNode is null"
								thisPost.parentNode.removeChild(thisPost);
						}
						var myregexp1 = culang.myregexp1;
						var myregexp2 = culang.myregexp2;
						var myregexp3 = culang.myregexp3;
						var myregexp4 = culang.myregexp4;
						var myregexp5 = culang.myregexp5;
						if (thisPost.innerHTML.match(myregexp1) || thisPost.innerHTML.match(myregexp2) || thisPost.innerHTML.match(myregexp3) || thisPost.innerHTML.match(myregexp4) || thisPost.innerHTML.match(myregexp5)) {
							if(thisPost.parentNode!==null) //TODO review error "thisPost.parentNode is null"
								thisPost.parentNode.removeChild(thisPost);
						}
					}
				}
			}
		}
		if (GlobalChatBox) {
			var chatPosts = document.evaluate(".//div[contains(@class,'chatwrap')]", GlobalChatBox, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
				if(chatPosts) for (var i = 0; i < chatPosts.snapshotLength; i++) {
				thisPost = chatPosts.snapshotItem(i);
				if(Options.DeleteRequest){
				var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
					if(helpAllianceLinks){
						for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
						thisLink = helpAllianceLinks.snapshotItem(j);
						thisLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(thisLink.parentNode.parentNode.parentNode.parentNode);
						}
					}
				}
			}
		} 
	},

}
// VAR WINMANAGER
var WinManager = {wins:{},didHide:[],get:function (prefix) {var t = WinManager;return t.wins[prefix];},
	add:function (prefix, pop) {
		var t = WinManager;
		t.wins[prefix] = pop;
		if (uW.cpopupWins == null)
			uW.cpopupWins = {};
		uW.cpopupWins[prefix] = pop;
	},
	hideAll:function () { var t = WinManager;t.didHide = [];for (k in t.wins) {if (t.wins[k].isShown()) {t.didHide.push(t.wins[k]);t.wins[k].show(false);}}},
	restoreAll:function () { var t = WinManager;
		for (var i = 0; i < t.didHide.length; i++)
			t.didHide[i].show(true);
			},delete:function (prefix) {var t = WinManager;delete t.wins[prefix];delete uW.cpopupWins[prefix];}
};
// VAR DELETE REPORTS
var DeleteReports = {
	trace:false, //set to 'true' to write a trace with logit
	deleting:false,
	deletes1:new Array(),
	deletes0:new Array(),
	timer:null,
	firstReport:null,
	stopAtReport:null, 
	
	init:function () {
		var t = DeleteReports;
		if(t.trace) logit("DeleteReports: init()")
		clearInterval(t.timer);
		if (!t.deleting && (Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs4 || Options.DeleteMsgs5 || Options.DeleteMsgs6 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3)) {
			if (parseIntNan(Options.DeleteTimerMinute) < 1) Options.DeleteTimerMinute = 1;
			t.timer = setInterval(t.startdeletereports, Options.DeleteTimerMinute * 60000);
			if(t.trace) logit("DeleteReports: setInterval "+ Options.DeleteTimerMinute * 60000);		
		}
	},

	startdeletereports:function () {
		var t = DeleteReports;
		if(t.trace) logit("DeleteReports: startdeletereports()")

		if(t.deleting) {
			if(t.trace) logit("DeleteReports: startdeletereports return >> deleting=true")
			return;
		}
		if (!(Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs4 || Options.DeleteMsgs5 || Options.DeleteMsgs6 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3)) {
			if(t.trace) logit("DeleteReports: startdeletereports return >> no Options checked")
			return;
		}
		
		t.firstReport=null;
		t.deletes1 = new Array();
		t.deletes0 = new Array();
		t.deleting = true;
		t.fetchreport(0, t.checkreports);
	},

	fetchreport:function (pageNo, callback) {
		var t = DeleteReports;
		if(t.trace) logit("DeleteReports: fetchreport(pageNo:"+pageNo+",callback)");
		var params = uW.Object.clone(uW.g_ajaxparams);
		if (pageNo > 1)
			params.pageNo = pageNo;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/listReports.php" + uW.g_ajaxsuffix, {
			method:"post",
			parameters:params,
			onSuccess:function (rslt) {
				if(t.trace) logit("DeleteReports: AjaxRequest(listReports.php) Success");
				callback(rslt, pageNo); // >> t.checkreports
			},
			onFailure:function () {
				if(t.trace) logit("DeleteReports: AjaxRequest(listReports.php) Failure");
				callback(); // >> t.checkreports
			},
		});
	},

	checkreports:function (rslt, pageNo) {
		var t = DeleteReports;
		if(t.trace) logit("DeleteReports: checkreports(rslt, pageNo:"+pageNo+")");
		
		var doParseReports = true;
		var doGetNextPage  = true;
		var totalPages     = 0;
		
		if (doParseReports && !rslt.ok) {
			if(t.trace) logit("\nDeleteReports: checkreports <?> !rslt.ok");
			// t.deleting = false; return;
			doParseReports=false;
		}
		if (doParseReports && typeof(rslt.arReports)=='undefined') {
			/* dump of rslt
			rslt: {}
				ok: true
				error_code: 9
				data: {}
			*/
			if(false) { // A - stop
				if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports == undefined"+"\n"+dump(rslt,"rslt")+"\nStop reading reports.");
				t.deleting = false; 
				return;
			}
			if(false) { // B - try again
				if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports == undefined"+"\n"+dump(rslt,"rslt")+"\nWaiting 1 min and try again");
				setTimeout(function(){t.fetchreport(pageNo, t.checkreports); },5000);			
				return;
			}
			if(true) { // C - skip the current page
				if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports == undefined"+"\n"+dump(rslt,"rslt")+"\nSkip current page");
				doParseReports=false;
			}
		}
		if (doParseReports && rslt.arReports.length < 1) {
			if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports.length < 1");
			// t.deleting = false; return;
			doParseReports=false;
		}
		
		if(doParseReports) {
			actionLog("" + culang.mainReports + "", "" + culang.reportDelete + " " + (pageNo + 1) + "/" + rslt.totalPages + " " + culang.reportDelete2 + "");
			var reports = rslt.arReports;
			totalPages = rslt.totalPages;

			for (k in reports) {
				/*
				reports["0r12345678"]: {} -->
					reportType: "0"
					reportId: "12345678"
					reportUnixTime: "1337530325"
					side0XCoord: "604"
					side0YCoord: "610"
					side0TileType: "51"
					side0TileLevel: "12"
					side0CityId: "56297"
					side0PlayerId: "14177235"
					side0AllianceId: "0"
					side1XCoord: "602"
					side1YCoord: "601"
					side1CityId: "38409"
					side1PlayerId: "9675639"
					side1AllianceId: "2288"
					marchType: "4"
					marchTypeState: "2"
					userId: "9675639"
					eventType: "0"
					subType: "0"
					reportStatus: "2"
					reportDetailId: "0"
				*/
				if(pageNo==0) t.firstReport=reports[k].reportId;
				//if(t.stopAtReport!==null && (reports[k].reportId<t.stopAtReport))doGetNextPage=false;
				//GM_log(dump(reports[k],"reports["+k+"]"));
			
				if (Options.DeleteMsg) {
					if ((reports[k].marchType == 9 || reports[k].marchType == 4) && reports[k].side0PlayerId == 0 && reports[k].side0TileType > 50)
						t.deletes1.push(k.substr(2));
					else if (reports[k].marchType == 1 && t.isMyself(reports[k].side1PlayerId))
						t.deletes1.push(k.substr(2));
				}
				if (Options.DeleteMsgs0) {
					if (reports[k].marchType == 1 && !t.isMyself(reports[k].side1PlayerId)) {
						t.deletes0.push(k.substr(2));
					}
				}
				if (Options.DeleteMsgs1) {
					if (reports[k].marchType == 4 && (reports[k].side0TileType <= 50) && reports[k].side0PlayerId == 0)
						t.deletes1.push(k.substr(2));
				}
				if (Options.DeleteMsgs2) {
					if (reports[k].side0TileType == 54)
						t.deletes1.push(k.substr(2));
				}
				if (Options.DeleteMsgs3) {
					if (reports[k].side0TileType == 51 && reports[k].marchType == 2 && t.isMyself(reports[k].side0PlayerId))
						t.deletes1.push(k.substr(2));
				}
				if (Options.DeleteMsgs4) {
					if (reports[k].side0TileType == 51 && reports[k].marchType == 3)
						t.deletes1.push(k.substr(2));
				}
				if (Options.DeleteMsgs5) {
					if (reports[k].side0TileType == 51 && reports[k].marchType == 4)
						t.deletes1.push(k.substr(2));
				}
				if (Options.DeleteMsgs6) {
					for (var i = 0; i < CrestData.length; i++) {
						x = CrestData[i].X;
						y = CrestData[i].Y;
						if (reports[k].side0XCoord == x && reports[k].side0YCoord == y) {
							t.deletes1.push(k.substr(2));
						}
					}
				}
				if (FarmOptions.DeleteReports) { //TODO check option
					for(var i=0; i<Cities.numCities; i++) {
            var x=Cities.cities[i].x;
            var y=Cities.cities[i].y;
            if (Tabs.farm.FarmArray[i+1]) 
							for (j=0;j<Tabs.farm.FarmArray[i+1].length;j++) 
								if (reports[k].side1XCoord == x && reports[k].side1YCoord == y && 
										reports[k].side0XCoord == Tabs.farm.FarmArray[i+1][j]["x"] && 
										reports[k].side0YCoord == Tabs.farm.FarmArray[i+1][j]["y"]) 
									t.deletes1.push(k.substr(2));
         	}	    
				}
							
			}
		} else {
			actionLog("" + culang.mainReports + "", "" + "Error reading reports from page " + (pageNo + 1));  //TODO multilang			
		}
		
		if ((pageNo + 1) == totalPages || parseInt(pageNo + 1) >= 10) {
			if (t.deletes1.length > 0 || t.deletes0.length > 0) {
				t.deleteCheckedReports(t.deletes1, t.deletes0);
			} else {
				actionLog("" + culang.mainReports + "", "" + culang.reportAutoDeleteNoNeed + "");
			}
			doGetNextPage=false;
		}
		
		if(doGetNextPage){
			t.fetchreport(pageNo + 1, t.checkreports);
		} else {
			if(t.firstReport!==null) t.stopAtReport=t.firstReport;
			t.deleting = false;
		}
		
	},
	deleteCheckedReports:function (deletes1, deletes0) {
		var t = DeleteReports;
		if(t.trace) logit("DeleteReports: deleteCheckedReports(["+t.deletes1.length+"],["+t.deletes0.length+"])");
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.s1rids = deletes1.join(",");
		params.s0rids = deletes0.join(",");
		params.cityrids = '';
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/deleteCheckedReports.php" + uW.g_ajaxsuffix, {
			method:"post",
			parameters:params,
			onSuccess:function (rslt) {
				if(t.trace) logit("DeleteReports: AjaxRequest(deleteCheckedReports.php) Success ok:"+rslt.ok==true);
				if (rslt.ok) {
					Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length) - parseInt(deletes0.length);
					actionLog("" + culang.mainReports + "", "" + culang.reportAutoDelete + " " + (parseInt(deletes1.length) + parseInt(deletes0.length)) + "");
				} else {
					actionLog("" + culang.mainReports + "", "" + culang.mainError + ": " + rslt.msg);
				}
				t.deleting = false;
			},
			onFailure:function () {
				if(t.trace) logit("DeleteReports: AjaxRequest(deleteCheckedReports.php) Failure");
				actionLog("" + culang.mainReports + "", "" + culang.mainError + ": " + rslt.msg);
				t.deleting = false;
			},
		});
	},
	isMyself:function (userID) {
		var t = DeleteReports;
		if (!Seed.players["u" + userID])
			return false;
		if (Seed.players["u" + userID].n == Seed.player.name)
			return true;
		else
			return false;
		return false;
	},
};
// VAR TAB MANAGER
var tabManager = {
	tabList : {},
	currentTab : null,
	init : function (mainDiv){
		var t = tabManager;
		var sorter = [];
		for (k in Tabs){
			if (!Tabs[k].tabDisabled){
				t.tabList[k] = {};
				t.tabList[k].name = k;
				t.tabList[k].obj = Tabs[k];
				if (Tabs[k].tabLabel != null)
					t.tabList[k].label = Tabs[k].tabLabel;
				else
					t.tabList[k].label = k;
				if (Tabs[k].tabOrder != null)
					sorter.push([Tabs[k].tabOrder, t.tabList[k]]);
				else
					sorter.push([1000, t.tabList[k]]);
				t.tabList[k].div = document.createElement('div');
			}
		}

		sorter.sort (function (a,b){return a[0]-b[0]});

		if (Options.pdxMenuLeft) {
			var m = '<div class=pdxMenu style="display:'+Options["powerMenuOptions"]+'; position:fixed; margin-left:-120px;margin-top:-36px;padding:2px; border: 1px outset #141516; border-radius:'+Options.popupBorderRadius+'; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee; box-shadow: 2px 2px 2px 2px #eee;"><TABLE cellspacing=0 cellpadding=0 class=multiMainTabs>';
			for (var i=0; i<sorter.length; i++){
				m += '<TR><TD class=spacer></td><TD class=ksTabNotSelLeft id=pbtc'+ sorter[i][1].name +'><A><SPAN class="multiTab">'+ sorter[i][1].label +'</span></a></td></tr>';
			}
			m+='</table></div>';
		} else {
			var m = '<TABLE cellspacing=0 cellpadding=0 class=multiMainTabs><TR>';
			for (var i=0; i<sorter.length; i++){
				m += '<TD class=spacer></td><TD class=ksTabNotSel id=pbtc'+ sorter[i][1].name +'><A><SPAN class="multiTab">'+ sorter[i][1].label +'</span></a></td>';
				if (i==9) m+='</tr><tr>';
				if (i==19) m+='</tr><tr>';
			}
			m+='</tr></table></div>';
		}

		mainPop.getMainTopDiv().innerHTML = m;

		for (k in t.tabList) {
			if (t.tabList[k].name == Options.currentTab)
				t.currentTab =t.tabList[k] ;
			ById('pbtc'+ k).addEventListener('click', this.e_clickedTab, false);
			var div = t.tabList[k].div;
			div.style.display = 'none';
			div.style.height = '100%';
			mainDiv.appendChild(div);
			try {
				t.tabList[k].obj.init(div);
			} catch (e){

			}
		}

		if (t.currentTab == null)
			t.currentTab = sorter[0][1];
		t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), true);
		t.currentTab.div.style.display = 'block';
	},

	hideTab : function (){
		var t = tabManager;
		t.currentTab.obj.hide();
	},

	showTab : function (){
		var t = tabManager;
		t.currentTab.obj.show();
	},

	setTabStyle : function (e, selected){
		if (selected){
			if (Options.pdxMenuLeft) {  e.className = 'ksTabSelLeft'; } else { e.className = 'ksTabSel'; }
		} else {
			if (Options.pdxMenuLeft) {  e.className = 'ksTabNotSelLeft'; } else { e.className = 'ksTabNotSel'; }
		}
	},

	e_clickedTab : function (e){
		var t = tabManager;
		newTab = t.tabList[e.target.parentNode.parentNode.id.substring(4)];
		if (t.currentTab.name != newTab.name){
			t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), false);
			t.setTabStyle (document.getElementById ('pbtc'+ newTab.name), true);
			t.currentTab.obj.hide ();
			t.currentTab.div.style.display = 'none';
			t.currentTab = newTab;
			newTab.div.style.display = 'block';
			Options.currentTab = newTab.name;
		}
		newTab.obj.show();
	},
}
//</editor-fold>


//<editor-fold desc="SPLIT:StringsArrays.js">
//	
//	   KOC POWER - STRING/ARRAY										        
//	


Array.prototype.compare = function (testArr) {if (this.length != testArr.length) return false;for (var i = 0; i < testArr.length; i++) {if (this[i].compare) {if (!this[i].compare(testArr[i])) return false;}if (this[i] !== testArr[i]) return false;}return true;};
Array.prototype.contains = function(val) {var i = this.length; while (i--) {if (this[i] == val) {return true;}}return false;}

String.prototype.stripTags = function () {return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');};
String.prototype.capitalize = function () {return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();};
String.prototype.mreplace = function(obj) {var ret = this.toString();for (k in obj) {var e = new RegExp('{'+k+'}',"g");ret = ret.replace(e, obj[k]);}return ret;}
String.prototype.StripQuotes = function () {return this.replace(/"/g, '');};
String.prototype.entityTrans = {  '&agrave;':'\\u00e0', '&eacute;':'\\u00e9', '&':'&amp;', '<':'&lt;',  '>':'&gt;',  '\"':'&quot;', '\'':'&#039', '<':'\\u003c', '/':'\\/', '\\':'\\\\', '\"':'\\\"','{':'&#123;','}':'&#125;'};
String.prototype.htmlEntities = function () {
	var ret = this.toString();
	for (k in this.entityTrans)
		ret = ret.split(k).join(this.entityTrans[k]);
	return ret;
};
String.prototype.htmlSpecialChars = function () {
	var ret = this.toString();
	for (k in this.entityTrans)
		ret = ret.split(k).join(this.entityTrans[k]);
	return ret;
};
String.prototype.htmlSpecialCharsDecode = function () {
	var ret = this.toString();
	for (k in this.entityTrans)
		ret = ret.split(this.entityTrans[k]).join(k);
	return ret;
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/GlobalFunc.js">
//	
//	   KOC POWER - GLOBAL FUNCTION										        
//	

function IncomingCheck(){
	var Counter=0;
	for (k in Seed.queue_atkinc) if (Seed.queue_atkinc[k].marchType==3 || Seed.queue_atkinc[k].marchType==4) Counter++;
	if (Counter==0 || Seed.queue_atkinc=="") document.getElementById('pbIncomingButton').style.display = "none";
	 else document.getElementById('pbIncomingButton').style.display = "inline";
}

function ClearMarchQueue(action){
	for (var c=1;c<=Seed.cities.length;c++){
		do {
			var check = false;
			for (var i=0;i<MarchQueue[c].length;i++) 
			if (((MarchQueue[c][i].what==undefined||MarchQueue[c][i].what==""+culang.mainAttack+"")?""+culang.mainAttack+"":MarchQueue[c][i].what)==action) {MarchQueue[c].splice(i,1);check=true;}
		} while (check);
	}
}
// GET SERVER ID
function getServerId(){if(myServerId==null){var a=/^[a-zA-Z]+([0-9]+)\./.exec(document.location.hostname);if(a)myServerId=a[1];else myServerId="??"}return myServerId}
// FB TOKEN FOR E-MAIL
function GetFbToken (){
	document.getElementById('KsFacebookConnect').innerHTML = '<IFRAME style="border:0;width:546px;max-width:600px;height:120px;max-height:130px;overflow:auto" src="http://kocscripts.com/koc/fb.html"></iframe>';
}
var cursorX;
var cursorY;
document.onmousemove = function(e){
	cursorX = e.pageX;
	cursorY = e.pageY;
	Options.MouseMove=unixTime();
	//RefreshEvery.setTimer();
}
document.onkeyup = function(e){
	Options.MouseMove=unixTime();
	//RefreshEvery.setTimer();
}

// remove Summoning Circle
function RemoveSummoningCircle(){
	var elem = document.getElementById('summoningCircleBanner');
	if (elem!=undefined && Options.KsSummonToggle) elem.style.display = "none";
}
// multibrowser 
function multiBrowserOverride(){
	if (!Options.pbAntiCheat) return;
	var old_updateSeed = uW.update_seed_ajax;
	var my_updateSeed = function (marchForceUpdateFlag, updateSeedDoneCallback, isCancelTraining) {
		delete uW.seed.ss;
		old_updateSeed(marchForceUpdateFlag, updateSeedDoneCallback, isCancelTraining);
	}
	uW.update_seed_ajax = my_updateSeed;
}
//if (Options.pbAntiCheat) {try {multiBrowserOverride();} catch (e) {}}

// eachSecond
function eachSecond (){
	Seconds++;
	//if (Seconds==2) multiBrowserOverride();
	//GMTclock
	if (Seconds%2==0 && Options.gmtClock) gmtClock.everySecond();
	//Alliance Report Watchdog
	if (Seconds%Options.WatchdogInterval==0 && Options.watchdog) WatchDog.FetchAllianceReports();
	//Overview Tab
	//Outgoing Marches 
	if (OutgoingMarches.active) OutgoingMarches.show();  
	//Incoming Marches 
	if (IncomingMarches.active) IncomingMarches.show();
	IncomingCheck();  
	//March Queue
	if (QueueMarches.active) QueueMarches.show();
	//Show Player & Might in map.
	if (Options.MapShowExtra) DrawLevelIcons();
	//Auto Build

	//Central March System
	FillMarchQueue();
	if (Seconds%MarchOffset==0) CheckMarchQueue();
	// Dashboard Tab
	if (Seconds%2==0) Dashboard.RPM();
	if (Seconds%2==0 && DashboardOptions.showWarnings) Dashboard.CheckForAlerts();
	if (GlobalOptions.pbWideScreenStyle=="wide" || GlobalOptions.pbWideScreenStyle=="ultra" || GlobalOptions.pbWideScreenStyle=="custom") {
	if (DashboardOptions.showRP) Dashboard.ShowRP();
		if (DashboardOptions.showMultiNote) Dashboard.multiNote();
		if (DashboardOptions.showStatus) Dashboard.CityStatus();
		if (DashboardOptions.showTower) Dashboard.ShowTowerAlerts();
		if (Seconds%2==0 && DashboardOptions.showLog) Dashboard.ShowLog();
		if (DashboardOptions.showSacrifice) Dashboard.showSacrifice();
	}	

	//Paint Raids
	Tabs.Raid.paint();	
	// Chat Stuff
	// if (Seconds%2==0) ChatPane.HandleChatPane();
	//Auto Refresh Seed
	// if (Seconds%300==0) RefreshSeed();
	//Check Gift
	// if (Seconds==10) Tabs.Gift.Check();	
	//Food Alert
	// if (Seconds%60==0) FoodAlerts.e_eachMinute();
	//Apothecary Tab
	// if (Seconds%30==0) Tabs.Apothecary.loop();

	//Get FB token for "Send to mail" app
	if (Seconds==2) GetFbToken();
	if (Seconds%3600==0) GetFbToken(); 
	//Replace Madmaxx TR switcher
	// if (Seconds==2) if (document.getElementById('t_throneStatList')) PaintKabamPresets();
	// if (Seconds==5) CheckForOtherScripts();
	ById('MouseMove').innerHTML = timestr(unixTime() - Options.MouseMove);
	//Remove Summoning Circle 
	if (Seconds==3) RemoveSummoningCircle();
}
function foo() { };
//Kabam Bug, der beim einloesen einen Items den Marsch Dialog blockiert
function checkunits() {
try {
	for(var i=0; i<Cities.numCities; i++) {
		var cityId = Cities.cities[i].id;
		var units = Seed.units['city'+cityId];
		if (units['unt'] != undefined) {
			delete(units['unt']);
		}
	}
} catch (ex) {
					alert('28842/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
}
}
//Maersche beenden, die bei "Warte auf Bericht" festhaengen
function checkmarches() {
	var now = unixTime();
	for(var i=0; i<Cities.numCities; i++) {
		var knights = [];
		var cityId = Cities.cities[i].id;
		var marches = Seed.queue_atkp['city'+cityId];
		for (var m in marches) {
			var march = marches[m];
			var mt = march.marchType;
			var ms = march.marchStatus;
			if (mt == 1 || mt == 3 || mt == 4) { //transport, spaehen, angriff
				if (isNaN(march.returnUnixTime)) var retUT = march.returnEta; 
					else var retUT = march.returnUnixTime;
				if ((ms == 5 && parseInt(retUT) < now) || (ms == 8 && (parseInt(retUT)+5) < now)) { //unbekannt oder beendet
					//Ritter freigeben 
					if (march.knightId != 0 && Seed.knights['city'+cityId]['knt'+march.knightId]) {
						Seed.knights['city'+cityId]['knt'+march.knightId].knightStatus = 1;
					}
					//Truppen zurueck geben - stimmen nicht 100%ig, weil Marsch haengt. Update-Seed sollte das aber richten
					for (var r = 1; r < 17; r++){
						Seed.units['city'+cityId]['unt'+r] = parseInt(Seed.units['city'+cityId]['unt'+r]) + parseInt(march['unit'+r+"Count"]);
					}
					//Marsch loeschen
					delete Seed.queue_atkp['city'+cityId][m];
					var rep = {
						'city' : Cities.byID[cityId].name,
					};
					actionLog(culang.mainMarches, culang.deleteMarch.mreplace(rep));
				}
			}
			//belegte Ritter speichern
			if (march.knightId != 0) knights.push(march.knightId);
		}
		//check, ob Ritter blockiert sind
		for (var k in Seed.knights['city'+cityId]) {
			var kn = Seed.knights['city'+cityId][k];
			if (kn.knightStatus == 10 && !knights.contains(kn.knightId)) {
				//Ritter freigeben
				kn.knightStatus = 1;
				var rep = {
					'city' : Cities.byID[cityId].name,
					'name' : kn.knightName,
				};
				actionLog(culang.mainMarches, culang.freeingKnight.mreplace(rep));
			}
		}
	}
}
//Werbebutton entfernen
function deleteButtons() {
	try {
	ById("dealSpotSwfStub").parentNode.removeChild(ById("dealSpotSwfStub"));
	} catch(e) {}
	try {
	ById("hudBottomContainer").parentNode.removeChild(ById("hudBottomContainer"));
	} catch(e) {}
	try {
	ById("hudTopContainer").parentNode.removeChild(ById("hudTopContainer"));
	} catch(e) {}
	try {
	ById("hudThirdContainer").parentNode.removeChild(ById("hudThirdContainer"));
	} catch(e) {}
}
//Merlin Fenster bei Start schliessen
merlincounter = 0;
function closeMerlin() {
	var m = ById("modal_mmb");
	if (m) {
		uW.Modal.hideModal();
	} else {
		merlincounter++;		
		if (merlincounter < 12) setTimeout(closeMerlin, 500);
	}
}
//Bugfix fuer Baufehler...
function Buildcheck() {
	var now = unixTime();
	for (var city in Seed.queue_con) {
		var cid = city.substr(4);
		//Auslassen der aktuellen Stadt
		//if (cid == uW.currentcityid) continue;
		var ai = Seed.queue_con[city];
		for (var aq = 0; aq < ai.length; aq++) {
			var q = ai[aq];
			if (q != null) {
				//Bau fertig?
				if (parseInt(q[4]) < now) {
					var typ = q[0];
					var level = q[1];
					var id = q[2];
					var pos = q[7];
					var baupos = Seed.buildings[city]['pos'+pos];
					//Build or Destroy?
					if (level > 0) {
						if (baupos[3] == id && baupos[0] == typ && parseInt(level) > parseInt(baupos[1])) {
							baupos[1] = level;
							Seed.queue_con[city].splice(aq,1);
							Seed.con_hlp['b'+id] = 0;
							if (cid == uW.currentcityid) {
								uW.update_bdg();
								uW.queue_changetab_building();
							}
						} 
					} else {
						if (baupos[3] == id && baupos[0] == typ && parseInt(baupos[1]) > 0) {
							delete baupos;
							Seed.queue_con[city].splice(aq,1);
							if (cid == uW.currentcityid) {
								uW.update_bdg();
								uW.queue_changetab_building();
							}
						}
					}
				}
			}
		}
	}
}
function onUnload(){
Options.ptWinPos=mainPop.getLocation();
Options.ptWin2Pos=mainPop2.getLocation();saveOptions();
if(!ResetColors)saveColors();
if(!ResetDFOption)saveDFOptions();
if(!ResetTabOptions)saveTabOptions(); }//saveLanguage();
function getAlliance (aid){
	if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
		return [''+culang.kocNeutral+'', 0, ''+culang.mainNone+''];
	else if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
		return [''+culang.kocFriendly+'',Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
	else if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
		return ['hostile',Seed.allianceDiplomacies.hostile['a'+aid].allianceId, Seed.allianceDiplomacies.hostile['a'+aid].allianceName];
}
function addScript (scriptText){
	var scr = document.createElement('script');
	scr.innerHTML = scriptText;
	document.body.appendChild(scr);
}
addScript ('uwuwuwFunc = function (text){ eval (text);  }');
function formatUnixTime(a,b){var c=uW.formatDateByUnixTime(a);return c}

function getResourceProduction (cityId){ 
	var now = unixTime();

	//Grundproduktion
	var workerFactor = 1;
	var c = parseIntNan(Seed.citystats["city" + cityId]["pop"][0]);  // akt. Einwohnerzahl
	var w = parseIntNan(Seed.citystats["city" + cityId]["pop"][3]);  // Arbeiter fuer 100% Produktion
	if (w > c) workerFactor = c / w;
	var base = [0,0,0,0,0];
	for (var i=1; i<5; i++){
		base[i] = parseIntNan(Seed.resources["city" + cityId]["rec" + i][2] * workerFactor);
	}
	//Ritterbonus
	knight1 = 0;
	var s = Seed.knights["city" + cityId];
	if (s) {
		s = s["knt" + Seed.leaders["city" + cityId].resourcefulnessKnightId];
		if (s){
			var knight1 = parseInt(s.resourcefulness);
			if (s.resourcefulnessBoostExpireUnixtime > now)
				knight1 *= 1.25;
		}
	}
	var knight = [0,0,0,0,0];
	for (var i=1; i<5; i++){
		knight[i] = parseIntNan(base[i]*knight1/100);
	}
	
	//Forschungsbonus
	var tech = [0,0,0,0,0];
	for (var i=1; i<5; i++){
		tech[i] = parseIntNan(base[i]*Seed.tech["tch" + i]/10);
	}
	
	//Wildnissbonus
	var wildinfo = [0,0,0,0,0];
	var w = Seed.wilderness["city" + cityId];
	for (var k in w){
		var type = parseIntNan(w[k].tileType);
		if (type==10 || type==11)
			wildinfo[1] += parseIntNan(w[k].tileLevel);
		else
			wildinfo[type/10] += parseInt(w[k].tileLevel);
	}
	var wild = [0,0,0,0,0];
	for (var i=1; i<5; i++){
		wildinfo[i] *= uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().REALLOCATED_LABOR, cityId, {
			type: i,
		});
		wildinfo[i] *= uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().GNOMISH_QUARRY_FOREMAN, cityId, {
			type: i,
		});
		wild[i] = parseIntNan(base[i]*wildinfo[i]*0.05);
	}
	
	//Fuersorgebonus
	var providence = [0,100,100,100,100];
	
	//Itembonus
	var item = [0,0,0,0,0];
	for (var i=1; i<5; i++){
		var items = 0;
		if (parseInt(Seed.playerEffects["r" + i + "BstExp"]) > now) {
			items = 0.25;
		}
		item[i] = parseIntNan(base[i]*items);
	}
	
	//Thronebonus
	var throne = [0,0,0,0,0];
	var MaxResProd = uW.cm.thronestats.boosts.ResourceProduction.Max;
	for (var i=1; i<5; i++){
		var TR = Math.min(uW.cm.ThroneController.effectBonus(82) + uW.cm.ThroneController.effectBonus(82 + i), MaxResProd) ;
		throne[i] = parseIntNan(base[i]*TR/100);
	}
	
	//Segenbonus
	var blessing = [0,0,0,0,0];
	for (var i=1; i<5; i++){
		var s = 0;
		if (i==2) s += uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().NATURE_GIFTS, cityId);
		blessing[i] = parseIntNan(base[i]*s);
	}
	
	//Waechterbonus???
	
	//Gesamtproduktion
	var ret = [0,0,0,0,0];	
	for (var i=1; i<5; i++){
		ret[i] = base[i] + knight[i] + tech[i] + wild[i] + providence[i] + item[i] + throne[i] + blessing[i];
	}

	return ret;
}

function actionLog (ou,msg){Tabs2.ActionLog.log (msg,ou);}
function IsNumeric(input) {return (input - 0) == input && input.length > 0;}
function parseIntNan (n){
	x = parseInt(n, 10);
	if (isNaN(x))
		return 0;
	return x;
}
function parseIntCommas (n){
	n = n.replace(THOUSANDS_SEP,'');
	n = n.replace(THOUSANDS_SEP,'');
	n = n.replace(THOUSANDS_SEP,'');	
	n = n.replace(THOUSANDS_SEP,'');
	n = n.replace(THOUSANDS_SEP,'');
	n = n.split(DEC_POINT);
	n = n.join('');
	x = parseInt(n, 10);
	if (isNaN(x))
		return 0;
	return x;
}
function parseIntZero (n){
	n = n.trim();
	if (n == '')
		return 0;
	return parseInt(n, 10);
}

// KOCNOTFOUND
function KOCnotFound(secs){
	var div;
	var countdownTimer = null;
	var endSecs = (new Date().getTime()/1000) + secs;

	div = document.createElement('div');
	div.innerHTML = '<DIV style="font-size:18px; background-color:#a00; color:#fff"><CENTER><BR>'+culang.kocNotFound+'<BR>\
      '+culang.refreshIn+' <SPAN id=pbwdsecs></span><BR><INPUT id=pbwdcan type=submit value="'+culang.mainCancel+'"><BR><BR></div>';
	document.body.insertBefore (div, document.body.firstChild);
	ById('pbwdcan').addEventListener('click', cancel, false);
	countdown();

	function countdown (){
		var secsLeft = endSecs - (new Date().getTime()/1000);
		ById('pbwdsecs').innerHTML = timestr(secsLeft);
		 if (secsLeft < 0) reloadKOC();
		countdownTimer = setTimeout (countdown, 1000);
	}
	function cancel (){
		clearTimeout (countdownTimer);
		document.body.removeChild (div);
	}
}
function clickWinKs(win,obj,evtName) {var evt = win.document.createEvent("MouseEvents");evt.initMouseEvent(evtName, true, true, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null);return !obj.dispatchEvent(evt);}
function searchDOM (node, condition, maxLevel, doMult){
	var found = [];
	eval ('var compFunc = function (node) { return ('+ condition +') }');
	doOne(node, 1);
	if(!doMult){
		if (found.length==0)
			return null;
		return found[0];
	}
	return found;
	function doOne (node, curLevel){
		try {
			if (compFunc(node))
				found.push(node);
		} catch (e){
		}
		if (!doMult && found.length>0)
			return;
		if (++curLevel<maxLevel && node.childNodes!=undefined)
			for (var c=0; c<node.childNodes.length; c++)
				doOne (node.childNodes[c], curLevel);
	}
}
function CwaitForElement (id, timeout, notify){
	this.check = check;
	this.end = new Date().getTime() + timeout;
	var t = this;
	this.check();
	function check(){
		if (document.getElementById(id))
			notify (true);
		else if (new Date().getTime() > t.end)
			notify (false);
		else
			setTimeout (t.check, 250);
	}
}
function CdialogCancelContinue (msg, canNotify, contNotify, centerElement){
	var pop = new CPopup ('ptcancont', 10, 10, 400,200, true, canNotify);
	if (centerElement)
		pop.centerMe(centerElement);
	else
		pop.centerMe(document.body);
	pop.getMainDiv().innerHTML = '<TABLE class=pdxTab align=center style="height: 100%"><TR align=center height=90%><TD>'+ msg +'</td></tr>\
      <TR align=center><TD><INPUT id=ptok type=submit value="'+culang.mainOK+'" \> &nbsp; &nbsp; </td></tr></table>';
	pop.getTopDiv().innerHTML = '<div class="popupBanner">'+ScriptName+'</div>';
	document.getElementById('ptok').addEventListener ('click', function (){pop.destroy(false); if (canNotify) canNotify();}, false);
	pop.show(true);
}

// OPTIONS FUNCTION

function MakeBlocks(getX, getY, radius) {
    var blocks = [];
    var xx = 0;
    var yy = 0;
    for (x = (getX - radius); x <= (getX + radius); x += 5) {
        for (y = (getY - radius); y <= (getY + radius); y += 5) {
            xx = x;
            yy = y;
            if (x > 750) xx -= 750;
            if (y > 750) yy -= 750;
            if (x < 0) xx += 750;
            if (y < 0) yy += 750;
            blocks.push("bl_" + xx + "_bt_" + yy);
        }
    }
    return blocks;
}

function MakeProvinceBlocks(getX, getY) {
    var blocks = [];
    var xx = 0;
    var yy = 0;
    for (x = getX; x <= (getX + 149); x += 5) {
        for (y = getY; y <= (getY + 149); y += 5) {
            xx = x;
            yy = y;
            blocks.push("bl_" + xx + "_bt_" + yy);
        }
    }
    return blocks;
}
function marchTimeCalculator(troops, is_round_trip, items_applied, cityID, action,dist) {
    if(dist=="NaN" || dist==0) return "N/A";
    var speed = 99999;
    var total_troops = 0;
    items_applied = items_applied || {};
    for(var troop_type in troops) {
        if(!troops[troop_type].toString().match(/^\d+$/)) continue;
        var troop_number = parseInt(troops[troop_type]);
        if(troop_number <= 0) continue;
        total_troops += troop_number;
        var troop_speed = parseInt(uW.unitstats["unt" + troop_type][3]);
        troop_speed *= (1 + 0.1 * parseInt(Seed.tech.tch11));
        if(uW.cm.unitHorsedBenefit[troop_type]) troop_speed = troop_speed * (1 + 0.05 * parseInt(Seed.tech.tch12))
         else {
            troop_speed *= (1 + 0.05 * (parseInt(Seed.tech2.tch1) || 0));
            troop_speed *= uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().BLOOD_LUST, cityID, {speed: true});
        }
        if(troop_speed < speed) speed = troop_speed;
    }
    speed *= uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().FILL_THE_RANKS, cityID, {marchspeed: true});
    speed *= uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().REDUCE_FATIGUE, cityID, {}); 
    var throne67 = uW.cm.ThroneController.effectBonus(67);  //March Speed
    var throne68, throne69, throne70, throne71, throne72;
    throne68 = throne69 = throne70 = throne71 = throne72 = 0;
    switch (action){
    	case 1: throne70 = uW.cm.ThroneController.effectBonus(70);break; //Transport March Speed
    	case 2: throne69 = uW.cm.ThroneController.effectBonus(69);break; //Reinforcement March Speed 
    	case 3: throne72 = uW.cm.ThroneController.effectBonus(72);break; //Scout March Speed
    	case 4: throne68 = uW.cm.ThroneController.effectBonus(68);break; //Attack March Speed
    	case 5: throne71 = uW.cm.ThroneController.effectBonus(71);break; //Reassign March Speed
    }
    var throneBoost = throne67 + throne68 + throne69 + throne70 + throne71 + throne72;
    speed = speed * (1 + (throneBoost * 0.01));
    var gi = uW.cm.guardianModalModel.getMarchBonus();
    var multiplier = 1 + (gi * 0.01);
    if(uW.cm.WorldSettings.isOn("GUARDIAN_MARCH_EFFECT")) speed = speed * multiplier;
    var time = 0;
    if(0 == speed || 0 == total_troops) return "N/A"; 
    time = Math.ceil(dist * 6000 / speed);
    if(items_applied["57"] && Seed.items.i57 > 0) time = parseInt(time * 0.5);
     else if(items_applied["55"] && Seed.items.i55 > 0) time = parseInt(time * 0.75);  
    if(uW.g_env !== "dev") time += 30;
    now = unixTime();        
    if(Seed.playerEffects.returnExpire >now) time = parseInt(time * 0.75);
    if(is_round_trip) time *= 2;    
    return timestr(time);
}
function getKnights(cityID,ktype){
    var knt = new Array();
		for (k in Seed.knights['city'+cityID]){
			if (Seed.knights['city'+cityID][k]["knightStatus"] == 1 && 
					Seed.leaders['city'+cityID]["resourcefulnessKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
					Seed.leaders['city'+cityID]["politicsKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
					Seed.leaders['city'+cityID]["combatKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
					Seed.leaders['city'+cityID]["intelligenceKnightId"] != Seed.knights['city'+cityID][k]["knightId"]){
				knt.push ({
					Name: Seed.knights['city'+cityID][k]["knightName"],
					ID: Seed.knights['city'+cityID][k]["knightId"],					
					Combat:	parseIntNan(Seed.knights['city'+cityID][k]["combat"]),
					Politics:	parseIntNan(Seed.knights['city'+cityID][k]["politics"]),
					Intelligence:	parseIntNan(Seed.knights['city'+cityID][k]["intelligence"]),
					Resourcefulness:	parseIntNan(Seed.knights['city'+cityID][k]["resourcefulness"]),
					Experience: parseIntNan(Seed.knights['city'+cityID][k]["experience"]),
				});
			}
		}
		knt = knt.sort(function sort(a,b) {
			var ac = a['Combat'];
			var bc = b['Combat'];
			var ap = a['Politics'];
			var bp = b['Politics'];
			var ai = a['Intelligence'];
			var bi = b['Intelligence'];
			var ar = a['Resourcefulness'];
			var br = b['Resourcefulness'];
			var as = a['Experience'];
			var bs = b['Experience'];
			switch(parseIntNan(ktype)) {
				case 0:
					var erg = ac == bc ? 0 : (ac < bc ? -1 : 1);
					break;
				case 1:
					var erg = ac == bc ? 0 : (ac > bc ? -1 : 1);
					break;
				case 2:
					var erg = ap == bp ? 0 : (ap < bp ? -1 : 1);
					break;
				case 3:
					var erg = ap == bp ? 0 : (ap > bp ? -1 : 1);
					break;
				case 4:
					var erg = ai == bi ? 0 : (ai < bi ? -1 : 1);
					break;
				case 5:
					var erg = ai == bi ? 0 : (ai > bi ? -1 : 1);
					break;
				case 6:
					var erg = ar == br ? 0 : (ar < br ? -1 : 1);
					break;
				case 7:
					var erg = ar == br ? 0 : (ar > br ? -1 : 1);
					break;	
				case 8:
					var erg = as == bs ? 0 : (as < bs ? -1 : 1);
					break;
				case 9:
					var erg = as == bs ? 0 : (as > bs ? -1 : 1);
					break;
			}
			return erg;
		});
    return knt; 
}
function getRallypoint(cityId){
	var rinfo = getRallypointInfo(cityId);
	return rinfo.maxMarches;
}
function doMarch(action,WhatCity){
try {
  var params = uW.Object.clone(uW.g_ajaxparams);
  params.cid=action.city;
  params.type=action.action;
  if (action.action == 4 || action.action == 5) {
		if (action.knight) var knight = getKnights(action.city, action.knight);
			else var knight = getKnights(action.city, 1);
		if (knight.toSource() == "[]") {
			var rep = {
				'type'		: action.what,
				'city' : Cities.byID[action.city].name,
			};
			actionLog(culang.marchLog,culang.marchLogErr1.mreplace(rep));		
			return;
		}
		params.kid=knight[0].ID;
	} else params.kid = 0;
  params.xcoord = action.targetX;
  params.ycoord = action.targetY;

  var TroopsOK = true;
	for (var i=1;i<=16;i++){
    var TroopsInCity = Seed.units['city'+action.city]['unt'+i];
    if (action[i]) {
    	if (parseInt(TroopsInCity) < parseIntNan(action[i])) {
				TroopsOK = false;
			} else if (parseIntNan(action[i]) > 0) params['u'+i] = action[i];
    }
  }
  if (!TroopsOK) {
  	MarchOffset = MarchDelay;
		var rep = {
			'type'		: action.what,
			'city' : Cities.byID[action.city].name,
		};
		actionLog(culang.marchLog,culang.marchLogErr2.mreplace(rep));		
   	return;
  }
	if (action.gold) params.gold = action.gold;
	if (action.r1) params.r1= action.r1;
	if (action.r2) params.r2= action.r2;
	if (action.r3) params.r3= action.r3;
	if (action.r4) params.r4= action.r4;
	if (action.r5) params.r5= action.r5;
	var rinfo = getRallypointInfo(action.city);
	var maxsend =  rinfo.maxMarchSize;
	
	var total=0;		
 	for (var i=1;i<=16;i++) total += parseIntNan(action[i]); 
  //	if (total == 'Nan')	actionlog('City: ' + WhatCity + ' - Troops: ' + total);	
  if (total == 0) {
  	MarchQueue[WhatCity].splice(0,1);
  	MarchOffset = MarchDelay;
		var rep = {
			'type'		: action.what,
			'city' : Cities.byID[action.city].name,
		};
		actionLog(culang.marchLog,culang.marchLogErr3.mreplace(rep));		
  	return;
  }
  if (total > maxsend) {
		MarchQueue[WhatCity].splice(0,1);
		var rep = {
			'type'		: action.what,
			'city' : Cities.byID[action.city].name,
		};
		actionLog(culang.marchLog,culang.marchLogErr4.mreplace(rep));		
		return;
	}
	//Marsch wird gesendet
	var tstring = '';
	for (var i=1;i<=16;i++){
		if (parseIntNan(action[i]) > 0) tstring += addCommas(action[i]) +' '+uW.unitcost['unt' + i][0]+', '
	}
	tstring = tstring.substring(0,tstring.length - 2);
	var rep = {
		'type'		: action.what,
		'city' 		: Cities.byID[action.city].name,
		'target' 	: action.targetX + ',' +action.targetY,
		'troops' 	: tstring,
	};
	actionLog(culang.marchLog,culang.marchLogSend.mreplace(rep));	
} catch (ex) {
					alert('29418/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
}	
  new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
    method: "post",
    parameters: params,
    loading: true,
    onSuccess: function (transport) {
      var rslt = eval("(" + transport.responseText + ")");
			if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
      if (rslt.ok) {
	      MarchesSend++;
				MarchQueue[WhatCity].splice(0,1);
				MarchOffset = MarchDelay;				
	      	var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
          var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
							unitsarr[i] = params["u"+i];
						}
					}
					var resources=new Array();
					resources[0] = params.gold;
					for(i=1; i<=4; i++){
						resources[i] = params["r"+i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};				//if (params.type == 1) MakeTransportLog(params);
      } else {
				MarchesError++;  			
        //if (rslt.error_code !=8 && rslt.error_code !=3 && rslt.error_code != 104) {
					var rep = {
						'type' : action.what,
						'city' : Cities.byID[params.cid].name,
						'error': '('+rslt.error_code+') '+rsltErrorCode(rslt),
					};
					actionLog(culang.marchLog,culang.marchLogErr5.mreplace(rep));		
				//}
        switch (rslt.error_code){
        	case 206: 
						//Cannot perform this action on target. Please try again later
						for (var k in Seed.wilderness['city'+action.city]) 
							if (Seed.wilderness['city'+action.city][k]['xCoord']==CrestOptions.X && Seed.wilderness['city'+action.city][k]['yCoord']==CrestOptions.Y) 
								Tabs.Crest.abandonWilderness(Seed.wilderness['city'+action.city][k]['tileId'],Seed.wilderness['city'+action.city][k]['xCoord'],Seed.wilderness['city'+action.city][k]['yCoord'],CrestOptions.CrestCity);
						MarchOffset = MarchDelay;
            break;
          case 213:
          	//Unable to use target Knight. Knight must be in the City to be used. If you receive this message in error, please refresh the game
          	MarchOffset = MarchDelay;
          	break;
          case 104: 
          	//Cannot perform this action on target location
          	MarchQueue[WhatCity].splice(0,1);
          	MarchOffset = MarchDelay;
          	break;
          case 0:
          	//Need to send at least one soldier", feedback:"Need to send at least one soldier
          	MarchQueue[WhatCity].splice(0,1);
          	MarchOffset = MarchDelay;
          	break;
        }
        if (rslt.user_action == "marchCaptcha") {
        	MarchOffset = 5*60; // 5 Minutes
					var rep = {
						'type'		: action.what,
					};
					actionLog(culang.marchLog,culang.marchLogErr6.mreplace(rep));		
        	document.getElementById('MarchesSendInfo').innerHTML += '&nbsp<span class="boldRed">CAPTCHA</span>';
        	//Captcha(params);
        } else MarchOffset = MarchDelay*2;
      }
      if (rslt.user_action != "marchCaptcha") {
       	var m = '<TABLE class=pdxTab><TR align=center><TD><b><u>'+culang.mainMarches+':</u></b> <img src=""/>';
       	m += "&nbsp" + MarchesSend + "&nbsp";
       	m += '&nbsp - &nbsp<img src=""/>';
      	m += "&nbsp" + MarchesError + '</td></tr></table>';
       	document.getElementById('MarchesSendInfo').innerHTML =  m;
			}
    },
    onFailure: function () {}
  });             
}
function MakeTransportLog(what){
    var params = uW.Object.clone(uW.g_ajaxparams);
	params.blocks = "bl_" + what.xcoord + "_bt_" + what.ycoord;
    new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
  		method: "post",
  		parameters: params,
  		onSuccess: function (rslt) {
    		if (rslt.ok) {
    			var userId = rslt.data["l_"+what.xcoord+"_t_"+what.ycoord].tileUserId;
				var targetCityName = rslt.data["l_"+what.xcoord+"_t_"+what.ycoord].cityName;
				var targetName = rslt.userInfo["u" + userId]["n"];
	    		for (var t=0;t<Seed.cities.length;t++) if (parseInt(Seed.cities[t][0]) == what.cid) var cityname = Seed.cities[t][1];
				var resources = 0;
			    if (what.gold) resources += parseInt(what.gold);
			   	if (what.r1) resources += parseInt(what.r1);
				if (what.r2) resources += parseInt(what.r2);
				if (what.r3) resources += parseInt(what.r3);
				if (what.r4) resources += parseInt(what.r4);
				if (what.r5) resources += parseInt(what.r5);
				var msg = "Transport: " + addCommas(resources) + " resources from " + cityname + " to: " + targetName + " (" + targetCityName + ')';
				actionLog(msg);
			}
  		},
	});	
}
function FillMarchQueue(){
	for (var ii=0;ii<Seed.cities.length;ii++){
		cityID = Seed.cities[ii][0];	
		//var rallypointlevel = getRallypoint(cityID);
		var rinfo = getRallypointInfo(cityID);
		var now = unixTime();
		// if (Tabs.Transport.traderState.running && (Options.lastCityTransport[ii+1]+(Options.transportinterval * 60)) < now) Tabs.Transport.doMarch(cityID,ii);
		if (MarchQueue[ii+1].length < rinfo.freeSlots) {
			// logit("FillMarchQueue 111111111111111111111111111111111111111");
			if (DFOptions.Running) var send = Tabs.DF.doMarch(cityID,ii); 	
			if (send) continue;
			if (WildOptions.Running) var send = Tabs.WildAttack.doMarch(cityID,ii);			
			if (AtkOptions.Running) Tabs.Attack.doMarch(cityID,ii);
			if (FarmOptions.Running) Tabs.farm.barbing(cityID,ii);
			// if (CrestOptions.Running) {			
				// for (var k in Seed.wilderness['city'+cityID]) if (Seed.wilderness['city'+cityID][k]['xCoord']==CrestOptions.X && Seed.wilderness['city'+cityID][k]['yCoord']==CrestOptions.Y) Tabs.Crest.abandonWilderness(Seed.wilderness['city'+cityID][k]['tileId'],Seed.wilderness['city'+cityID][k]['xCoord'],Seed.wilderness['city'+cityID][k]['yCoord'],CrestOptions.CrestCity);
				// Tabs.Crest.FirstRound();
			// }
		}
	}
}
function CheckMarchQueue(){
	var RP = getRallypoint(Seed.cities[WhatCity-1][0]);
	var MarchesRunning = CheckCityMarches(WhatCity-1);
	var total = 0;
	for (var i=1;i<=Seed.cities.length;i++) total += MarchQueue[i].length;
	if (total == 0) return;
	if (MarchQueue[WhatCity].length > 0) {
		if (MarchesRunning < (RP-Options.RPClip)) doMarch(MarchQueue[WhatCity][0],WhatCity);
		if (MarchQueue[WhatCity][0].what != "WildW1") WhatCity++;
		if (WhatCity >= (Seed.cities.length+1)) WhatCity = 1;
	}
	else {
		WhatCity++;
		if (WhatCity >= (Seed.cities.length+1)) WhatCity = 1;
		CheckMarchQueue();
	}
}
function CheckCityMarches(City){
	var Counter=0;
	var cityID = Seed.cities[City][0];
	var now=unixTime();
	if (Seed.queue_atkp['city'+ cityID] != undefined) for (atkp in Seed.queue_atkp['city'+ cityID]) if (Seed.queue_atkp['city'+ cityID][atkp]["marchId"] || Seed.queue_atkp['city'+ cityID][atkp]["returnUnixTime"]>now) Counter++;
	return Counter;
}
function Captcha (params){
    captchawin = new CPopup ('pbmarch_captcha', 0, 0, 400, 300, true);
    captchawin.centerMe (mainPop.getMainDiv);
    var m = "<CENTER><SPAN class=boldRed>"+culang.marchHeadCaptchaAlertNote+"</span></center><br \><CENTER><div class=\"captcha_container\"><form id=pbmarch_captchaform ></form></div></center>";
    captchawin.getMainDiv().innerHTML = m;
    captchawin.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.marchHeadCaptchaAlert+'</div>';

    captchawin.show(true);
  
    uW.Recaptcha.create("6LcT7cQSAAAAAG4whvbBz60hGjJg0ON1wRIRv_iD", "pbmarch_captchaform", {
        callback: function(){
            uW.Recaptcha.focus_response_field();
            $("pbmarch_captchaform").addEventListener("submit", function(e){
                e.preventDefault();
                e.stopPropagation();
                params.marchWarning = 1;
                params.marchCaptcha_challenge = uW.Recaptcha.get_challenge();
                params.marchCaptcha_response = uW.Recaptcha.get_response();
				MarchOffset = MarchDelay;
                captchawin.destroy();
            }, false);
        },
        theme: "white"
    });
    return;
}
uW.pdxGotoMap = function (x, y){
	setTimeout (function (){
		ById('mapXCoor').value = x;
		ById('mapYCoor').value = y;
		uW.reCenterMapWithCoor();
		var a = ById("mod_views").getElementsByTagName("a");
		for (var b = 0; b < a.length; b++) {
			a[b].className = ""
		}
		ById('mod_views_map').className = "sel";
		ById("maparea_city").style.display = 'none';
		ById("maparea_fields").style.display = 'none';
		ById("maparea_map").style.display = 'block';
		uW.tutorialClear()
	}, 0);
};

// KOC MAP
Map = {
	/***
	 0: bog
	 10: grassland
	 11: lake
	 20: woods
	 30: hills
	 40: mountain
	 50: plain
	 51: city / barb
	 53: misted city
	 ***/
	generateBlockList : function(left, top, width) {
		var width5 = parseInt(width / 5);
		var bl = [];

		for (x=0; x<width5; x++){
			xx = left + (x*5);
			if (xx > 745)
				xx -= 750;
			for (y=0; y<width5; y++){
				yy = top + (y*5);
				if (yy > 745)
					yy -= 750;
				bl.push ('bl_'+ xx +'_bt_'+ yy);
			}
		}
		return bl.join(",");
	},

	callback : null,
	request : function (left, top, width, cb) {
		left = parseInt(left / 5) * 5;
		top = parseInt(top / 5) * 5;
		width = parseInt((width+4) / 5) * 5;
		var blockString = this.generateBlockList(left, top, width);
		Map.callback = cb;
		if (uW.SANDBOX)
			return RequestMAPTEST(left, top, width, callback);
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = blockString;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				Map.callback(left, top, width, rslt);
			},
			onFailure: function (rslt) {
				Map.callback(left, top, width, rslt);
			}
		});
	},
};

// 0:bog, 10:grassland, 11:lake, 20:woods, 30:hills, 40:mountain, 50:plain, 51:city / barb, 53:misted city
function CMapAjax (){
	this.normalize = normalize;
	this.request = request;

	function request (left, top, width, notify){
		var left = parseInt(left / 5) * 5;
		var top = parseInt(top / 5) * 5;
		var width = parseInt((width+4) / 5) * 5;

		var blockString = generateBlockList(left, top, width);
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = blockString;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				notify(left, top, width, rslt);
			},
			onFailure: function (rslt) {
				notify(left, top, width, rslt);
			}
		});
		function generateBlockList (left, top, width) {
			var width5 = parseInt(width / 5);
			var bl = [];
			for (x=0; x<width5; x++){
				var xx = left + (x*5);
				if (xx > 745)
					xx -= 750;
				for (y=0; y<width5; y++){
					var yy = top + (y*5);
					if (yy > 745)
						yy -= 750;
					bl.push ('bl_'+ xx +'_bt_'+ yy);
				}
			}
			return bl.join(",");
		}
	}

	function normalize  (x){
		if ( x >= 750)
			x -= 750;
		else if (x < 0)
			x += 750;
		return parseInt (x/5) * 5;
	}
}
function FullDateTime(str){	var time = new Date(str*1000);D = addZero(time.getDate());M = addZero(time.getMonth()+1);Y = addZero(time.getFullYear());h = addZero(time.getHours());m = addZero(time.getMinutes());s = addZero(time.getUTCSeconds());var fullDate =  D +"/"+ M +"/"+ Y +"  "+ h + ":" + m + ":" + s;return fullDate;}
function addZero(i){if (i<10) i="0" + i;return i;}
function getMaxLoad(unitType,unitCount) {
		var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
		var loadEffectBoost = 0;
		if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
		var loadBoost = uW.cm.ThroneController.effectBonus(6) + loadEffectBoost;
		if (uW.cm.unitFrontendType[unitType]=="siege") {
			loadBoost += uW.cm.ThroneController.effectBonus(59);
			//if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
		} else {
			if (uW.cm.unitFrontendType[unitType]=="horsed") {
				loadBoost += uW.cm.ThroneController.effectBonus(48);
			}
		}
		var MaxLoad = uW.cm.thronestats.boosts.Load.Max;
		var TR = Math.min(loadBoost, MaxLoad) / 100;
		var load = parseInt(unitCount*parseInt(uW.unitstats["unt"+unitType][5]) * (1 + TR + techLoadBoost));
    return load;
};
function distance (d, f, c, e) {
	var a = 750;
	var g = a / 2;
	var b = Math.abs(c - d);
	if (b > g)
		b = a - b;
	var h = Math.abs(e - f);
	if (h > g)
		h = a - h;
	return Math.round(100 * Math.sqrt(b * b + h * h)) / 100;
};
function setTabStyle (e, selected){
	if (selected){
		if (Options.pdxMenuLeft) {  
			e.className = 'ksTabSelLeft'; 
		} else { 
			e.className = 'ksTabSel'; 
		}
	} else {
		if (Options.pdxMenuLeft) { 
			e.className = 'ksTabNotSelLeft'; 
		} else { 
			e.className = 'ksTabNotSel'; 
		}
	}
}
function clickedTab2 (e){
	who2 = e.target.id.substring(3);
	newObj2 = Tabs2[who2];
	if (Tabs2[currentName2]==undefined) {currentName2 = 'Movement';}
	currentObj2 = Tabs2[currentName2];
	if (currentName2 != who2){
		setTabStyle (document.getElementById ('ab'+currentName2), false);
		setTabStyle (document.getElementById ('ab'+who2), true);
		if (currentObj2){
			currentObj2.hide ();
			currentObj2.getContent().style.display = 'none';
			}
		currentName2 = who2;
		Options.currentTab2 = currentName2;
		cont = newObj2.getContent();
		newObj2.getContent().style.display = 'block';
	}
	newObj2.show();
}
function mouseMainTab (me){if (me.button == 2){var c = getClientCoords (ById('main_engagement_tabs'));mainPop.setLocation ({x: c.x+4, y: c.y+c.height});}}
function eventHideShow (){if (mainPop.toggleHide(mainPop)){tabManager.showTab();Options.pbWinIsOpen = true;}else{tabManager.hideTab();Options.pbWinIsOpen = false;}saveOptions();}
function hideMe (){mainPop.show (false);tabManager.hideTab();Options.pbWinIsOpen = false;saveOptions();}
function showMe (){mainPop.show (true);tabManager.showTab();Options.pbWinIsOpen = true;saveOptions();}
function mouseMainTab2 (me){if (me.button == 2){var c = getClientCoords (ById('main_engagement_tabs'));mainPop2.setLocation ({x: c.x+4, y: c.y+c.height});}}
function eventHideShow2 (){if (mainPop2.toggleHide(mainPop2)){if (Tabs2[currentName2]==undefined) {currentName2 = 'Movement';}Tabs2[currentName2].show();Options.ptWin2IsOpen = true;} else {if (Tabs2[currentName2]==undefined) {currentName2 = 'Movement';}Tabs2[currentName2].hide();Options.ptWin2IsOpen = false;}saveOptions();}
function reloadKOC (){
	var serverId = getServerId();
	if(serverId == '??') window.location.reload(true);
	var addl='';
	/*
	if (LangOptions.culang) {
	addl="&lang="+LangOptions.culang;
	}
	*/
	var goto = window.location.protocol+'//apps.facebook.com/kingdomsofcamelot/?s='+serverId+''+addl;
	if(document.URL.match(/standalone=1/i)){
		goto = window.location.protocol+'//www.kabam.com/kingdoms-of-camelot/play?s='+serverId+''+addl;
	}	
	var t = '<FORM target="_top" action="'+ goto +'" method=post><INPUT id=xxpbButReload type=submit value=RELOAD><INPUT type=hidden name=s value="'+ serverId +'"</form>';
	var e = document.createElement ('div');
	e.innerHTML = t;
	document.body.appendChild (e);
	setTimeout (function (){document.getElementById('xxpbButReload').click();}, 0);
}
function getResearchLevels () {
	for (var t=1; t < 18; t++) {
		if (t != 7) {
			researchLevels[t] = {};
			researchLevels[t].Id = t;
			researchLevels[t].Name = uW.techcost['tch'+t][0].replace (/&#39;/img, '\'');
			researchLevels[t].Level = parseInt(Seed.tech['tch'+t]);
			researchLevels[t].NextLevelETA = 0;
			researchLevels[t].Image = 'https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/tech/'+t+'_s33.png';
		}
	}
	var q;
	var now = unixTime();
	for(var i=0; i<Cities.numCities; i++) { // each city
		var cityID = 'city'+ Cities.cities[i].id;
		q = Seed.queue_tch[cityID];
		if (q[0] != undefined)
			researchLevels[parseInt(q[0][0])].NextLevelETA = parseInt(q[0][3]) - now;
	}
}
function getResearchLevels2 () {
	for (var t=1; t < 7; t++) {
		researchLevels2[t] = {};
		researchLevels2[t].Id = t;
		researchLevels2[t].Name = uW.techcost2['tch'+t][0].replace (/&#39;/img, '\'');
		researchLevels2[t].Level = parseInt(Seed.tech2['tch'+t]);
		researchLevels2[t].NextLevelETA = 0;
		researchLevels2[t].Image = 'https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/tech2/'+t+'_s33.png';
	}
	var q;
	var now = unixTime();
	for(var i=0; i<Cities.numCities; i++) { // each city
		var cityID = 'city'+ Cities.cities[i].id;
		q = Seed.queue_tch2[cityID];
		if (q[0] != undefined)
			researchLevels2[parseInt(q[0][0])].NextLevelETA = parseInt(q[0][3]) - now;
	}
}
function getTroopDefTrainEstimates(cityID){
	var city = {};
	var b = Seed.buildings['city' + cityID];
	city.numBarracks = 0;
	city.maxBarracks = 0;
	city.numDruidBarracks = 0;
	city.maxDruidBarracks = 0;
	city.numFeyBarracks = 0;
	city.maxFeyBarracks = 0;
	city.numBritonBarracks = 0;
	city.maxBritonBarracks = 0;
	city.totLevelsBarracks = 0;
	city.totLevelsAscBarracks = 0;
	city.blacksmithLevel = 0;
	city.stableLevel = 0;
	city.workshopLevel = 0;
	city.wallLevel = 0;
	for (var g in b) {
		var building = b[g];
		var btype = parseIntNan(building[0]);
		var blvl = parseIntNan(building[1]);
		if (btype == 13) {                            //Kaserne
			city.numBarracks++;
			city.totLevelsBarracks += parseInt(blvl);
			if (blvl > city.maxBarracks) city.maxBarracks = blvl;
		}
		if (btype == 22) {                            //Asc Kaserne
			city.numDruidBarracks++;
			city.totLevelsDruidBarracks += parseInt(blvl);
			if (blvl>city.maxDruidBarracks) city.maxDruidBarracks = blvl;
		}
		if (btype == 24) {                            //Asc Kaserne
			city.numFeyBarracks++;
			city.totLevelsFeyBarracks += parseInt(blvl);
			if (blvl>city.maxFeyBarracks) city.maxFeyBarracks = blvl;
		}
		if (btype == 26) {                            //Asc Kaserne
			city.numBritonBarracks++;
			city.totLevelsBritonBarracks += parseInt(blvl);
			if (blvl>city.maxBritonBarracks) city.maxBritonBarracks = blvl;
		}
		if (btype == 15) city.blacksmithLevel = blvl;	//Schmied
		if (btype == 16) city.workshopLevel = blvl;   //Werkstatt
		if (btype == 17) city.stableLevel = blvl;     //Stallung
		if (btype == 19) city.wallLevel = blvl;       //Mauer
	}

	//Forschungslevel
	city.loggingLevel = parseInt(Seed.tech["tch2"]);
	city.geometryLevel = parseInt(Seed.tech["tch5"]);
	city.eagleEyesLevel = parseInt(Seed.tech["tch6"]);
	city.poisonedEdgeLevel = parseInt(Seed.tech["tch8"]);
	city.metalAlloysLevel = parseInt(Seed.tech["tch9"]);
	city.featherweightPowderLevel = parseInt(Seed.tech["tch10"]);
	city.alloyHorseshoesLevel = parseInt(Seed.tech["tch12"]);
	city.fletchingLevel = parseInt(Seed.tech["tch13"]);
	city.giantsStrengthLevel = parseInt(Seed.tech["tch16"]);
	
	//Ritter
	var now = unixTime();
	city.marshallCombatScore = 0;
	city.foremanBasePoliticsScore = 0;
	city.foremanCombatScore = 0;	
	var s = Seed.knights['city'+cityID];
	if (s) {
		s = s["knt" + Seed.leaders['city'+cityID].combatKnightId];
		if (s){
			city.marshallCombatScore = s.combat;
			if (s.combatBoostExpireUnixtime > now)
				city.marshallCombatScore *= 1.25;
		}
	}
	var s = Seed.knights['city'+cityID];
	if (s) {
		s = s["knt" + Seed.leaders['city'+cityID].politicsKnightId];
		if (s) {
			city.foremanBasePoliticsScore = s.politics;
			city.foremanCombatScore = s.combat;
			if (s.politicsBoostExpireUnixtime > now)
				city.foremanBasePoliticsScore *= 1.25;
				city.foremanCombatScore *= 1.25;
		}
	}
	
	//Berechnen der Ausbildungszeiten fuer Truppen
	for (var b = 1; b < 17; b++) {
		city['Troop'+b+'Time'] = TroopTrainTime(b, 10000, cityID);
		if (b == 1 && !(city.maxBarracks > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 2 && !(city.maxBarracks > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 3 && !(city.maxBarracks > 1 && city.eagleEyesLevel > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 4 && !(city.maxBarracks > 1 && city.poisonedEdgeLevel > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 5 && !(city.maxBarracks > 2 && city.workshopLevel > 0 && city.metalAlloysLevel > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 6 && !(city.maxBarracks > 3 && city.fletchingLevel > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 7 && !(city.maxBarracks > 4 && city.stableLevel > 0 && city.alloyHorseshoesLevel > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 8 && !(city.maxBarracks > 6 && city.workshopLevel > 4 && city.stableLevel > 4 && city.alloyHorseshoesLevel > 4)) city['Troop'+b+'Time'] = 0;
		if (b == 9 && !(city.maxBarracks > 5 && city.stableLevel > 0 && city.blacksmithLevel > 2 && city.featherweightPowderLevel > 0)) city['Troop'+b+'Time'] = 0;
		if (b == 10 && !(city.maxBarracks > 7 && city.stableLevel > 1 && city.blacksmithLevel > 4 && city.geometryLevel > 4 && city.fletchingLevel > 5)) city['Troop'+b+'Time'] = 0;
		if (b == 11 && !(city.maxBarracks > 8 && city.workshopLevel > 4 && city.stableLevel > 2 && city.blacksmithLevel > 6 && city.metalAlloysLevel > 7 && city.geometryLevel > 6)) city['Troop'+b+'Time'] = 0;
		if (b == 12 && !(city.maxBarracks > 9 && city.stableLevel > 1 && city.blacksmithLevel > 8 && city.geometryLevel > 9 && city.fletchingLevel > 9)) city['Troop'+b+'Time'] = 0;
		if (b == 13 && !(uW.cm.PrestigeModel.isPrestige(cityID) && uW.cm.PrestigeModel.getPrestigeFactionClass(cityID) == "druid")) city['Troop'+b+'Time'] = 0;
		if (b == 14 && !(uW.cm.PrestigeModel.isPrestige(cityID) && uW.cm.PrestigeModel.getPrestigeFactionClass(cityID) == "fey")) city['Troop'+b+'Time'] = 0;
		if (b == 15 && !(uW.cm.PrestigeModel.isPrestige(cityID) && uW.cm.PrestigeModel.getPrestigeFactionClass(cityID) == "briton")) city['Troop'+b+'Time'] = 0;
		if (b == 16 && !(city.maxBarracks > 10 && city.metalAlloysLevel > 9 && city.fletchingLevel > 10)) city['Troop'+b+'Time'] = 0;
	}
	
	var def = [53,55,60,61,62];
	for (var i = 0; i < def.length; i++) {
		var fort = def[i];
		city['Def'+fort+'Time'] = WallsTrainTime(fort, 10000, cityID);
		if (fort == 53 && !(city.wallLevel > 5 && city.blacksmithLevel > 5 && city.fletchingLevel > 4)) city['Def'+fort+'Time']  = 0;
		if (fort == 55 && !(city.wallLevel > 7 && city.blacksmithLevel > 7 && city.fletchingLevel > 6 && city.geometryLevel > 6)) city['Def'+fort+'Time']  = 0;
		if (fort == 60 && !(city.wallLevel > 3 && city.blacksmithLevel > 3 && city.poisonedEdgeLevel > 1)) city['Def'+fort+'Time']  = 0;
		if (fort == 61 && !(city.wallLevel > 0 && city.metalAlloysLevel > 0)) city['Def'+fort+'Time']  = 0;
		if (fort == 62 && !(city.wallLevel > 1 && city.blacksmithLevel > 1 && city.loggingLevel > 1)) city['Def'+fort+'Time']  = 0;
	}
	
	return city;
}

// n -> Truppentyp, p -> Anzahl, city -> CityID
function TroopTrainTime(n, p, city) {
	if (p < 1) return 0;
	var h = +(uW.unitcost["unt" + n][7]) * p,
		c, f = {}, g = Seed.buildings["city" + city],
		b = {}, e = Seed.knights["city" + city],
		l, q = Seed.leaders["city" + city];
	f.barracks = 0;
	f.workshop = 0;
	f.stable = 0;
	f.tech = 0;
	f.knight = 0;
	f.ultimate = 0;
	for (var u in g) {
		var t = g[u];
		t.id = +(t[0]);
		t.level = parseInt(+(t[1]));
		var s = (parseInt(n) == 13 || parseInt(n) == 14 || parseInt(n) == 15);
		t.isPrestige = (parseInt(t[2]) >= 100 && parseInt(t[2]) <= 105);
		if ((t.id === 13 || t.id === 22 || t.id === 24 || t.id === 26) && t.level > 0) {
			if ((s && t.isPrestige) || (!s && !t.isPrestige)) {
				f.barracks += (t.level + 9)
			}
		}
		if (t.id === 16 && t.level > 0) {
			if (+(n) >= 9 && +(n) < 13) {
				f.workshop = t.level
			}
		}
		if (t.id === 17 && t.level > f.stable) {
			if (+(n) >= 7 && +(n) < 13) {
				f.stable = t.level
			}
		}
	}
	c = f.barracks / 10;
	h = Math.max(1, Math.ceil(h / c));
	c = 1;
	if (e) {
		l = e["knt" + q.combatKnightId];
		if (l) {
			f.knight = (+(l.combatBoostExpireUnixtime) - unixTime() > 0) ? (l.combat * 1.25) : l.combat
		} else {
			f.knight = 0
		}
	}
	if (Seed.tech) {
		f.tech = Seed.tech.tch5
	}
	f.ultimate = parseInt(f.workshop) + parseInt(f.stable) + parseInt(f.tech);
	c = c * (1 + (0.1 * f.ultimate) + (0.005 * f.knight));
	var d = uW.cm.ThroneController.effectBonus(77);
	c = c * (1 + (d / 100));
	//Guardianbonus
	if (uW.cm.WorldSettings.isOn("GUARDIAN_MARCH_EFFECT")) {
		//var SPD={0:0,1:1,2:1,3:2,4:2,5:3,6:3,7:4,8:5,9:7,10:10,11:20,12:35};
		var SPD={0:0,1:5,2:5,3:10,4:10,5:15,6:15,7:20,8:25,9:35,10:70,11:130,12:250};
		var b1=0,y=false,v=false,w=0;
		var mm=Seed.guardian;
		for (var ii in mm) {
			var ww = mm[ii];
			if (ww.cityId==city) {
				if (ww.type== "stone") y=true;
				if (ww.guardianCount==4) v=true;
				var level=0;
				if (ww.cityGuardianLevels.stone!=undefined) level = ww.cityGuardianLevels.stone;
				w = SPD[level] / 100;
				var w2 = (uW.cm.ThroneController.getBoundedEffect(106) / 100);
				var bx = 0;
				if (y && v) {
					bx = 1.5;
				}
				if (y && !v) {
					bx = 1;
				}
				if (!y && v) {
					bx = 0.5;
					w2 = 0;
				}
				if (!y && !v) {
					bx = 0;
					w2 = 0;
				}
				b1 = w * bx;
				c = c * (1 + b1 + w2)
			}
		}
	}
	h = Math.max(1, Math.ceil(h / c));
	
	if (uW.cm.PrestigeModel.isPrestige(city)) {
		var a = uW.cm.PrestigeModel.getPrestigeLevel(city);
		if (a > 0) {
			var m = uW.cm.WorldSettings.getSetting("ASCENSION_BARRACKS_BOOST"),
				k = JSON.parse(m),
				o = k.values[a - 1][1],
				i = parseFloat(o);
			h = Math.ceil(h * i)
		}
	}
	//Blessing DEATH_FROM_AFAR
	var r = uW.cm.BlessingSystemModel.isBlessingActive(uW.cm.BlessingSystemModel.getBlessing().DEATH_FROM_AFAR, city);
	if (n == 6 && r) {
		h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().DEATH_FROM_AFAR, city, {})))
	}
	//Blessing EXPEDITED_SENTENCING 
	h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().EXPEDITED_SENTENCING, city, {
		traintime: true,
		unitid: n,
	})));
	//Blessing TO_THE_FRONT_LINES
	h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().TO_THE_FRONT_LINES, city, {
		unitid: n,
	})));
	//Blessing PRIORITIZED_CONSTRUCTION
	h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().PRIORITIZED_CONSTRUCTION, city, {
		unittype: n,
	})));
	//VIP?
	if (uW.cm.VipModel.isActive()) {
		var s = uW.cm.VipModel.getBoostValue("benefitTraining");
		h = Math.ceil(h - (h * (s / 100)))
	}
	return h
}

// d -> Befestigungstyp, e -> Anzahl, city -> CityID
function WallsTrainTime(d, e, city) {
	var b = parseInt(parseInt(uW.fortcost["frt" + d][7])) * e;
	var f = 1;
	f += 0.1 * parseInt(Seed.tech.tch16);
	var a = 0;
	var c = Seed.knights["city" + city];
	if (c) {
		c = c["knt" + Seed.leaders["city" + city].politicsKnightId];
		if (c) {
			a = parseInt(c.combat);
			newkntlv = ((parseInt(c.politicsBoostExpireUnixtime) - unixTime()) > 0) ? (a * 1.25) : a;
			f = f + (0.005 * newkntlv)
		}
	}

	b = Math.max(1, Math.ceil(b / f));
	//Neue Forschungen
	if (typeof Seed.tech2 !== "undefined") {
		if (typeof Seed.tech2.tch3 !== "undefined") {
			var c = (1 - parseFloat(Seed.tech2.tch3) * 0.05);
			b = Math.max(1, Math.ceil(b * c));
		}
	}
	return b
}
function setCities(){
	var il = uW.itemlist;
	for (var i=1101; i < 1115; i++)
		crestname[i] = il['i'+i].name
	getResearchLevels();
	Cities.numCities = Seed.cities.length;
	Cities.cities = [];
	Cities.byID = {};
	for (i=0; i<Cities.numCities; i++){
		city = {};
		city.idx = i;
		city.id = parseInt(Seed.cities[i][0]);
		city.name = Seed.cities[i][1];
		city.x = parseInt(Seed.cities[i][2]);
		city.y = parseInt(Seed.cities[i][3]);
		city.tileId = parseInt(Seed.cities[i][5]);
		city.provId = parseInt(Seed.cities[i][4]);
		getTroopDefTrainEstimates('city'+ city.id, city.id);
		Cities.cities[i] = city;
		Cities.byID[Seed.cities[i][0]] = city;
	}
}
function officerId2String (oid){
	if (oid==null)
		return '';
	else if (oid==3)
		return uW.allianceOfficerTypeMapping[3];
	else if (oid==2)
		return uW.allianceOfficerTypeMapping[2];
	else if (oid==1)
		return uW.allianceOfficerTypeMapping[1];
	else if (oid==4)
		return uW.allianceOfficerTypeMapping[4];
	return '';
}
function DouW(func, execute_by_embed) {if(this.isChrome || execute_by_embed) {var scr=document.createElement('script');scr.innerHTML=func;document.body.appendChild(scr);} else {
		try {eval("uW."+func);} catch (error) {logit("A javascript error has occurred when executing a function via DouW. Error description: "+error.description);}}}
function GetDisplayName(){var DisplayName = ById('topnavDisplayName');if(DisplayName){DisplayName = DisplayName.innerHTML;}else{DisplayName = null;}return DisplayName;}
function entier_1dec (nombre){if (parseInt(nombre*10)!=0){return parseInt(nombre*10)/10;}else{return nombre;}}
	// a.className='button20';
var tileNames = {
	'city' : culang.mainCity,
	'lake' : culang.kocLake,
	'grassland' : culang.kocGrassland,
	'plain' : culang.kocPlain,
	'woods' : culang.kocForests,
	'hills' : culang.kocHill,
	'mountain' : culang.kocMount,
	'bog' : culang.kocBog,
	'bcity' : culang.kocBarbarianCamps,
	'boss' : culang.kocDarkForest,
}
function DrawLevelIcons() {
	var maptileRe = /modal_maptile.([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)/;
	var mapwindow = document.getElementById('mapwindow');
	if (!mapwindow) return;
	var levelIcons = document.getElementById('levelIcons');
	if (levelIcons) return;

	var ss = document.evaluate(".//a[contains(@class,'slot')]", mapwindow, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var idDone = false;
	for (var s = 0; s < ss.snapshotLength; s++) {
		var a = ss.snapshotItem(s);
		var onclick = a.getAttribute('id');
		//alert(onclick);
		var owner = '';
		if (onclick) {
			// logit(onclick);
			var tileinfo = uW.g_mapObject.model.getTileActions(onclick)["tileClick"];
			//logit(inspect(tileinfo));
			if (tileinfo) {
				var might = parseInt(tileinfo.might);
				var alliance = parseIntNan(tileinfo.allianceId);
				var dip = getDiplomacy(alliance);
				var province = uW.provincenames['p'+ tileinfo.province]
				owner = tileinfo.username;
			}
		}
		var sp = a.getElementsByTagName('span');
		if (sp.length == 0) continue;

		if (!idDone) {
			a.id = 'levelIcons';
			idDone = true;
		}
		sp[0].style.color = 'white';
		sp[0].style.fontSize = '10px';
		sp[0].style.textShadow = '0.2em 0.2em 0.1em black';

		if (Options.MapShowExtra) {
			if (tileinfo.username != "null") {
				if (tileinfo.alliance != null) {
					if (dip == culang.kocHostile) sp[0].style.color = 'red';
					sp[0].innerHTML = 'Lvl: ' + tileinfo.level + ' / ' + province + '<br>' + owner + '<br>' + addCommas(might) +'<br>'+tileinfo.alliance;
				} else {
					sp[0].style.color = 'yellow';
					sp[0].innerHTML = 'Lvl: ' + tileinfo.level + ' / ' + province + '<br>' + owner + '<br>' + addCommas(might);
				}
			} else 
				sp[0].innerHTML = 'Lvl: ' + tileinfo.level + ' / ' + province;
		} 
	}
}
function GetProvince(x,y){
	if(x>=  0 && x<=149 && y>=  0 && y<=149) return "Tintagel";
	if(x>=150 && x<=299 && y>=  0 && y<=149) return "Cornwall";
	if(x>=300 && x<=449 && y>=  0 && y<=149) return "Astolat";
	if(x>=450 && x<=599 && y>=  0 && y<=149) return "Lyonesse";
	if(x>=  0 && x<=149 && y>=150 && y<=299) return "Paimpont";
	if(x>=150 && x<=299 && y>=150 && y<=299) return "Cameliard";
	if(x>=300 && x<=449 && y>=150 && y<=299) return "Sarras";
	if(x>=450 && x<=599 && y>=150 && y<=249) return "Canoel";
	if(x>=600 && x<=749 && y>=150 && y<=299) return "Avalon";
	if(x>=  0 && x<=149 && y>=300 && y<=449) return "Carmathen";
	if(x>=150 && x<=299 && y>=300 && y<=449) return "Shallott";
	if(x>=450 && x<=599 && y>=300 && y<=449) return "Cadbury";
	if(x>=600 && x<=749 && y>=300 && y<=449) return "Glastonbury";
	if(x>=  0 && x<=149 && y>=450 && y<=599) return "Camlann";
	if(x>=150 && x<=299 && y>=450 && y<=599) return "Orkney";
	if(x>=300 && x<=449 && y>=450 && y<=599) return "Dore";
	if(x>=150 && x<=299 && y>=  0 && y<=149) return "Cornwall";
	if(x>=450 && x<=599 && y>=450 && y<=599) return "Logres";
	if(x>=600 && x<=749 && y>=450 && y<=599) return "Caerleon";
	if(x>=  0 && x<=149 && y>=600 && y<=749) return "Parmenie";
	if(x>=150 && x<=299 && y>=600 && y<=749) return "BodminMoor";
	if(x>=300 && x<=449 && y>=600 && y<=749) return "Cellwig";
	if(x>=450 && x<=599 && y>=600 && y<=749) return "Listeneise";
	if(x>=600 && x<=749 && y>=600 && y<=749) return "Albion";
	else return "?"
}
function CdispCityPicker (id, span, dispName, notify, selbut, disable_list){
	function CcityButHandler (t){
		var that = t;
		this.clickedCityBut = clickedCityBut;
		function clickedCityBut (e){
			if (that.selected != null)
				that.selected.className = "castleBut castleButNon";
			that.city = Cities.cities[e.target.id.substr(that.prefixLen)];
			if (that.dispName)
				ById(that.id+'cname').innerHTML = that.city.name;
			e.target.className = "castleBut castleButSel";
			that.selected = e.target;
			if (that.coordBoxX){
				that.coordBoxX.value = that.city.x;
				that.coordBoxY.value = that.city.y;
				that.coordBoxX.style.backgroundColor = '#ffffff';
				that.coordBoxY.style.backgroundColor = '#ffffff';
			}
			if (that.notify != null)
				that.notify(that.city, that.city.x, that.city.y);
		}
	}

	function selectBut (idx){ById(this.id+'_'+idx).click();}

	function bindToXYboxes (eX, eY){
		function CboxHandler (t){
			var that = t;
			this.eventChange = eventChange;
			if (that.city){
				eX.value = that.city.x;
				eY.value = that.city.y;
			}
			function eventChange (){
				var xValue=that.coordBoxX.value.trim();
				var xI=/^\s*([0-9]+)[\s,]+([0-9]+)/.exec(xValue);
				if(xI) {
					that.coordBoxX.value=xI[1]
					that.coordBoxY.value=xI[2]
				}
				var x = parseInt(that.coordBoxX.value, 10);
				var y = parseInt(that.coordBoxY.value, 10);
				if (isNaN(x) || x<0 || x>750){
					that.coordBoxX.style.backgroundColor = '#ff8888';
					return;
				}
				if (isNaN(y) || y<0 || y>750){
					that.coordBoxY.style.backgroundColor = '#ff8888';
					return;
				}
				that.coordBoxX.style.backgroundColor = '#ffffff';
				that.coordBoxY.style.backgroundColor = '#ffffff';
				if (that.notify != null)
					that.notify (null, x, y);
			}
		}
		this.coordBoxX = eX;
		this.coordBoxY = eY;
		var bh = new CboxHandler(this);
		eX.size=2;
		eX.maxLength=10;
		eY.size=2;
		eY.maxLength=3;
		eX.addEventListener('change', bh.eventChange, false);
		eY.addEventListener('change', bh.eventChange, false);
	}

	this.selectBut = selectBut;
	this.bindToXYboxes = bindToXYboxes;
	this.coordBoxX = null;
	this.coordBoxY = null;
	this.id = id;
	this.dispName = dispName;
	this.prefixLen = id.length+1;
	this.notify = notify;
	this.selected = null;
	this.city = null;
	var m = '';
	for (var i=0; i<Cities.cities.length; i++){
		if(matTypeof(disable_list) == 'array'){
			if(disable_list[i])
				m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit DISABLED \>';
			else
				m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
		} else
			m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
	}
	if (dispName)
		m += ' &nbsp; <SPAN style="display:inline-block; width:85px; font-weight:bold;" id='+ id +'cname' +'></span>';
	span.innerHTML = m;
	var handler = new CcityButHandler(this);
	for (var i=0; i<Cities.cities.length; i++)
		document.getElementById(id+'_'+i).addEventListener('click', handler.clickedCityBut, false);
	if (selbut != null)
		this.selectBut(selbut);
}

var pop = null;
function dialogRetry (errMsg, seconds, onRetry, onCancel, errCode){
	seconds = parseInt(seconds);
	if (pop == null) {
		pop = new CPopup ('Ksptretry', 0, 0, 400,300, true);

		pop.getTopDiv().innerHTML = '<div class="popupBanner">'+ScriptName+'</div>';
		pop.getMainDiv().innerHTML = '<CENTER><BR><FONT COLOR=#550000><B>'+culang.multiErrorPopup+'</b></font><BR><BR><DIV id=KsparetryErrMsg></div>\
         <BR><BR><B>'+culang.kocDialogRetry+' <SPAN id=KsparetrySeconds></b></span> '+culang.mainSeconds+' ...<BR><INPUT id=KsparetryCancel type=submit value="'+culang.mainCancel+'" \>';
		ById('KsparetryCancel').addEventListener ('click', doCancel, false);

	}
	pop.show(true);
	pop.centerMe(mainPop.getMainDiv());
	/*if(errCode && uW.g_js_strings.errorcode['err_'+errCode]) {
	 if (document.getElementById('KsparetryErrMsg')) {
	 if (uW.g_js_strings.errorcode['err_'+errCode]) 
	 document.getElementById('KsparetryErrMsg').innerHTML = uW.g_js_strings.errorcode['err_'+errCode];
	 else
	 document.getElementById('KsparetryErrMsg').innerHTML ="Erreur : "+ errMsg;
	 }
	 } else
	 if (document.getElementById('KsparetryErrMsg')) document.getElementById('KsparetryErrMsg').innerHTML = errMsg;*/
	if(errCode && uW.g_js_strings.errorcode['err_'+errCode])
		if (ById('KsparetryErrMsg')) ById('KsparetryErrMsg').innerHTML = uW.g_js_strings.errorcode['err_'+errCode];
		else
			document.getElementById('KsparetryErrMsg').innerHTML = errMsg;
	if (document.getElementById('KsparetrySeconds')) document.getElementById('KsparetrySeconds').innerHTML = seconds;
	var rTimer = setTimeout (doRetry, seconds*1000);
	countdown ();

	function countdown (){
		if (document.getElementById('KsparetrySeconds')) ById('KsparetrySeconds').innerHTML = seconds--;
		if (seconds > 0)
			cdTimer = setTimeout (countdown, 1000);
	}
	function doCancel(){clearTimeout (rTimer);clearTimeout (cdTimer);pop.destroy();onCancel ();}
	function doRetry (){clearTimeout (rTimer);clearTimeout (cdTimer);pop.show(false);onRetry();}
}
function GM_AjaxGet (url, args, notify, label){GM_xmlhttpRequest({method: "get",url: addUrlArgs(url, args),onload: function (rslt) {notify (rslt.responseText);},onerror: function () {notify (null);},});}
function GM_AjaxPost (url, args, notify, label){GM_xmlhttpRequest({method: "post",url: url,data: implodeUrlArgs(args),headers:{"Content-Type": "application/x-www-form-urlencoded",'X-Requested-With': 'XMLHttpRequest','X-Prototype-Version': '1.6.1','Accept': 'text/javascript, text/html, application/xml, text/xml, */*'},onload: function (rslt) {notify (rslt.responseText);},onerror: function () {notify (null);},});}
function AjaxRequest (url, opts){
	var headers = {'X-Requested-With': 'XMLHttpRequest',
								 'X-Prototype-Version': '1.7.1',
								 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*',};
	var ajax = new XMLHttpRequest();
	
	if (opts.method==null || opts.method=='') method = 'GET';
	else method = opts.method.toUpperCase();

	if (method == 'POST'){headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';} else if (method == 'GET'){addUrlArgs (url, opts.parameters);}
	
	ajax.onreadystatechange = function(){
		if (ajax.readyState==4) {
			if (ajax.status == 200) {
				if (opts.onSuccess) opts.onSuccess(ajax);
			} else {
				actionLog(culang.logSelectMoreError, "<span class='boldRed'>Ajax Error: </span>Status = " + ajax.status);
				if (opts.onFailure) opts.onFailure(ajax);
			}
		} else {
			if (opts.onChange) opts.onChange (ajax);
		}
	}
	ajax.open(method, url, true);
	for (var k in headers)
		ajax.setRequestHeader (k, headers[k]);
	if (matTypeof(opts.requestHeaders)=='object')
		for (var k in opts.requestHeaders)
			ajax.setRequestHeader (k, opts.requestHeaders[k]);

	if (method == 'POST'){
		var a = [];
		for (k in opts.parameters){
			if(matTypeof(opts.parameters[k]) == 'object')
				for(var h in opts.parameters[k])
					a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
			else
				a.push (k +'='+ opts.parameters[k] );
		}
		ajax.send (a.join ('&'));
	} else               {
		ajax.send();
	}
}
function getOffset( el ) {var _x = 0;var _y = 0;while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {_x += el.offsetLeft - el.scrollLeft;_y += el.offsetTop - el.scrollTop;el = el.offsetParent;}return { top: _y, left: _x };}
function implodeUrlArgs (obj){
	var a = [];
	for (var k in obj)
		a.push (k +'='+ encodeURI(obj[k]) );
	return a.join ('&');
}
function addUrlArgs (url, args){
	if (!args)
		return url;
	if (url.indexOf('?') < 0)
		url += '?';
	else if (url.substr(url.length-1) != '&')
		url += '&';
	if (matTypeof(args == 'object'))
		return url + implodeUrlArgs (args);
	return url + args;
}
function AjaxRequest2 (url, opts){
	var headers = {
		'X-Requested-With': 'XMLHttpRequest',
		'X-Prototype-Version': '1.7.1',
		'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
	};
	var ajax = new XMLHttpRequest();
	
	if (opts.method==null || opts.method=='')
		method = 'GET';
	else
		method = opts.method.toUpperCase();
	if (method == 'POST'){
		headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
	} else if (method == 'GET'){
		addUrlArgs (url, opts.parameters);
	}
	ajax.onreadystatechange = function(){
		if (ajax.readyState==4) {
			if (ajax.status == 200) {
				if (opts.onSuccess) opts.onSuccess(ajax);
			} else {
				if (opts.onFailure) opts.onFailure(ajax);
				actionLog(culang.logSelectMoreError, "<span class='boldRed'>Ajax Error: </span>Status = " + ajax.status);
			}
		} else {
			if (opts.onChange) opts.onChange (ajax);
		}
	}
	ajax.open(method, url, true);
	for (var k in headers)
		ajax.setRequestHeader (k, headers[k]);
	if (matTypeof(opts.requestHeaders)=='object')
		for (var k in opts.requestHeaders)
			ajax.setRequestHeader (k, opts.requestHeaders[k]);
	if (method == 'POST'){
		var a = [];
		for (k in opts.parameters){
			if(matTypeof(opts.parameters[k]) == 'object'){
				for(var h in opts.parameters[k]){
					if(matTypeof(opts.parameters[k][h]) == 'object'){
						for(var i in opts.parameters[k][h]){
							if(matTypeof(opts.parameters[k][h][i]) == 'object'){
								for(var j in opts.parameters[k][h][i]){
									a.push (k+'['+h+']['+i+']['+j+'] ='+ opts.parameters[k][h][i][j] );
								}
							} else
								a.push (k+'['+h+']['+i+']'+' ='+ opts.parameters[k][h][i]);
						}
					} else
						a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
				}
			} else
				a.push (k +'='+ opts.parameters[k] );
		}
		ajax.send (a.join ('&'));
	} else {
		ajax.send();
	}
}
function MyAjaxRequest (url, o, noRetryX){
	var opts = uW.Object.clone(o);
	var wasSuccess = o.onSuccess;
	var wasFailure = o.onFailure;
	var retry = 0;
	var delay = 3;
	var show=true;
	var silentTimer;
	var noRetry = noRetry===true?true:false;
	opts.onSuccess = mySuccess;
	opts.onFailure = myFailure;
	new AjaxRequest(url, opts);
	return;

	function myRetry(){
		++retry;
		if (retry>5) {
			actionLog(""+culang.logSelectMoreError+"", "<font color=red>"+culang.errorQuery+"</font>");
			return false;
		}
		new AjaxRequest(url, opts);

		delay = delay * 1.20;
	}
	function myFailure(){
		var o = {};
		o.ok = false;
		o.errorMsg = "AJAX Communication Failure";
		wasFailure (o);
	}
	function mySuccess (msg){
		//logit(msg);
		var rslt;
		try {
			rslt = JSON2.parse(msg.responseText);
		} catch(e) {

			rslt = {"ok":true,"error_code":9,"data":[], "json": msg,};
			actionLog(""+culang.logSelectMoreError+"", "JSON-Error: "+msg.responseText);
		}
		var x;
		/*
		if (window.EmulateAjaxError){
			rslt.ok = false;
			rslt.error_code=8;
		}
		*/
		if (rslt.updateSeed) { try {uW.update_seed(rslt.updateSeed);} catch (e) {} }
		if (rslt.ok){
			wasSuccess (rslt);
			return;
		}

		rslt.errorMsg = uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));

		if (!noRetry && (rslt.error_code==0 ||rslt.error_code==8 || rslt.error_code==1 || rslt.error_code==3)){
			actionLog(culang.mainError, "<font color=res>"+ msg.responseText +"</font>");
			dialogRetry (inspect(rslt.errorMsg), delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code);
		} else if (!noRetry && rslt.error_code==9) {
			silentTimer = setTimeout(silentRetry, delay*100);
		} else {
			wasSuccess (rslt);
		}
	}
	function silentRetry() {clearTimeout(silentTimer);myRetry();}
}
function getDiplomacy (aid) {
	if (Seed.allianceDiplomacies == null)
		return ''+culang.kocNeutral+'';
	if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
		return ''+culang.kocFriendly+'';
	if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
		return ''+culang.kocHostile+'';
	if (aid == Seed.allianceDiplomacies.allianceId)
		return ''+culang.kocAllys+'';
	return ''+culang.kocNeutral+'';
};
function getMyUserId (){return parseInt([Seed.tutorial.userId]);}
function getMyAlliance (){
	if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
		return [0, ''+culang.mainNone+''];
	else
		return [Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
}
function UniteKMG(nb) {
	if (Math.abs(nb)>1000000000)
		val="<span title='"+addCommas(nb)+"'>" + addCommas((nb/1000000000).toFixed(2)) +" "+culang.shortBillion+"</span>";
	else if (Math.abs(nb)>1000000)
		val="<span title='"+addCommas(nb)+"'>" + addCommas((nb/1000000).toFixed(2)) +" "+culang.shortMillion+"</span>";
	else if (nb==0)
		val="0";
	else
		val=addCommas(nb);

	return val;
}
function getMarchInfoBOT(cityID){
	var ret = {};
	ret.marchUnits = [];
	ret.returnUnits = [];
	ret.resources = [];
	for (i=0; i<18; i++){
		ret.marchUnits[i] = 0;
		ret.returnUnits[i] = 0;
	}
	for (i=0; i<6; i++){
		ret.resources[i] = 0;
	}
	for (k in Seed.queue_atkp[cityID]){
		march = Seed.queue_atkp[cityID][k];
		if(march.marchType != 5){
			if (typeof (march) == 'object'){
				for (ii=0; ii<18; ii++){
					ret.marchUnits[ii] += parseInt (march['unit'+ ii +'Count']);
					ret.returnUnits[ii] += parseInt (march['unit'+ ii +'Return']);
				}
				for (ii=1; ii<6; ii++){
					if (march['r'+ ii] && parseInt(march['r'+ ii]) > 0) {
						ret.resources[ii] += parseInt(march['r'+ ii]);
					} else {
						ret.resources[ii] += parseInt(march['resource'+ ii]);
					}
				}
				if (march['g'] && parseInt(march['g']) > 0) {
					ret.resources[0] += parseInt(march['g']);
				} else {
					ret.resources[0] += parseInt(march['gold']);
				}
			}
		}
	}
	return ret;
}
function getMarchInfo (){
	var ret = {};
	ret.marchUnits = [];
	ret.returnUnits = [];
	ret.resources = [];
	for (i=0; i<18; i++){
		ret.marchUnits[i] = 0;
		ret.returnUnits[i] = 0;
	}
	for (i=0; i<6; i++){
		ret.resources[i] = 0;
	}
	var now = unixTime();
	for(i=0; i<Cities.numCities; i++) {   // each city
		cityID = 'city'+ Cities.cities[i].id;
		for (k in Seed.queue_atkp[cityID]){   // each march
			march = Seed.queue_atkp[cityID][k];
			if (typeof (march) == 'object'){
				for (ii=0; ii<18; ii++){
					ret.marchUnits[ii] += parseInt (march['unit'+ ii +'Count']);
					ret.returnUnits[ii] += parseInt (march['unit'+ ii +'Return']);
				}
				for (ii=1; ii<6; ii++){
					if (march['r'+ ii] && parseInt(march['r'+ ii]) > 0) {
						ret.resources[ii] += parseInt(march['r'+ ii]);
					} else {
						ret.resources[ii] += parseInt(march['resource'+ ii]);
					}
				}
				if (march['g'] && parseInt(march['g']) > 0) {
					ret.resources[0] += parseInt(march['g']);
				} else {
					ret.resources[0] += parseInt(march['gold']);
				}
			}
		}
	}
	return ret;
}
function getCityBuilding (cityId, buildingId){
	var b = Seed.buildings['city'+cityId];
	var ret = {count:0, maxLevel:0};
	for (var i in b) {
		var building = b[i];
		if (building[0] == buildingId){
			++ret.count;
			if (parseInt(building[1]) > ret.maxLevel)
				ret.maxLevel = parseInt(building[1]);
		}
	}
	return ret;
}
function logit (msg){
	var serverID = getServerId();
	var now = new Date();
	//	GM_log (serverID +' @ '+ now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +': '+  msg);
	GM_log ('\n' + now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +' @ ' + serverID + ': '+ '\n'+ msg);
}


// SAVE AND READ
function saveOptions(){var a=getServerId();GM_setValue("KsOptions_"+a,JSON2.stringify(Options))}
function saveTrainingOptions(){var a=getServerId();setTimeout(function(){GM_setValue("TrainingOptions_"+a,JSON2.stringify(TrainOptions))	},0)}
function saveFarmOptions() {var serverID = getServerId();setTimeout(function () {GM_setValue('FarmOptions_' + serverID, JSON2.stringify(FarmOptions));},0);}
function saveThroneOptions() {var serverID = getServerId();setTimeout(function () { GM_setValue('ThroneOptions_' + serverID, JSON2.stringify(ThroneOptions)); }, 0);}
function saveLangOptions (){setTimeout (function (){GM_setValue ('LangOptions_', JSON2.stringify(LangOptions));}, 0);}
function saveColors (){var serverID = getServerId();GM_setValue('Colors', JSON2.stringify(Colors));}
function saveUpgradeData (){var serverID = getServerId();setTimeout (function (){GM_setValue ('UpgradeData_'+serverID, JSON2.stringify(upgradeData));}, 0);}
function saveCombatOptions (){var serverID = getServerId();setTimeout (function (){GM_setValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CombatOptions));}, 0);}
function saveApothecaryOptions (){var serverID = getServerId();setTimeout (function (){GM_setValue ('ApothecaryOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(ApothecaryOptions));}, 0);}
function saveTabOptions (){  var serverID = getServerId();  setTimeout (function (){GM_setValue ('TabOptions_'+serverID, JSON2.stringify(TabOptions));}, 0);}
function saveKsRange (){ var serverID = getServerId();setTimeout (function (){GM_setValue ('KsRange_'+serverID, JSON2.stringify(KsRange));}, 0);}
function saveMarchOptions (){  var serverID = getServerId();  setTimeout (function (){GM_setValue ('MarchOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(MarchOptions));}, 0);}
function saveDashboardOptions (){var serverID = getServerId(); setTimeout (function (){GM_setValue ('DashboardOptions_'+serverID, JSON2.stringify(DashboardOptions));}, 0);}
function saveCrestData (){var serverID = getServerId();	setTimeout (function (){GM_setValue ('CrestData_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CrestData));}, 0);}

function readOptions(){var a=getServerId();s=GM_getValue("KsOptions_"+a);if(s!=null){opts=JSON2.parse(s);for(k in opts)Options[k]=opts[k]}}
function readFarmOptions() {
    var serverID = getServerId();
    s = GM_getValue('FarmOptions_' + serverID);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object') for (kk in opts[k])
            FarmOptions[k][kk] = opts[k][kk];
            else FarmOptions[k] = opts[k];
        }
    }
}
function readThroneOptions() {
	var serverID = getServerId();
	s = GM_getValue('ThroneOptions_' + serverID);
	if (s != null) {
		opts = JSON2.parse(s);
		for (k in opts) {
			if (matTypeof(opts[k]) == 'object') {
				//if(typeof(ThroneOptions[k])='undefined') continue;//skip unknown (old?) option, DANGEROUS!
				//if(k=='saveXitems'    )continue;
				//if(k=='SalvagePercent')continue;
				//if(k=='SalvageQuality')continue;
				//if(k=='SalvageAdvisor'||k=='SalvageBanner'||k=='SalvageChair'||k=='SalvageTable'||k=='SalvageWindow')continue;
				//if(k=='SalvagePreview')continue;
				//if(k=='Salvage'       )continue;
				if(typeof(ThroneOptions[k])=='undefined') ThroneOptions[k]={};
				for (kk in opts[k])	{
					if (matTypeof(opts[k][kk]) == 'object') {
						if(typeof(ThroneOptions[k][kk])=='undefined') ThroneOptions[k][kk]={};
						for (kkk in opts[k][kk]){
							ThroneOptions[k][kk][kkk] = opts[k][kk][kkk];
						}
					}else ThroneOptions[k][kk] = opts[k][kk];
				}
			}
			else ThroneOptions[k] = opts[k];
		}

		var filter=ThroneOptions.SalvageV2.EffectFilter;
		for (i in uW.cm.thronestats.effects) {
			if(typeof(filter[i])=='undefined') filter[i]={IsEnabled:false,IsEnabled2:false,IsEnabled3:false,Value:''};
			if(typeof(filter[i].IsEnabled ) == "undefined" || filter[i].IsEnabled ===null) filter[i].IsEnabled =false;
			if(typeof(filter[i].IsEnabled2) == "undefined" || filter[i].IsEnabled2===null) filter[i].IsEnabled2=false;
			if(typeof(filter[i].IsEnabled3) == "undefined" || filter[i].IsEnabled3===null) filter[i].IsEnabled3=false;
			if(typeof(filter[i].Percent   ) == "undefined" || filter[i].Percent   ===null) filter[i].Percent   ='';
			if(typeof(filter[i].PercentAdvisor) == "undefined") filter[i].PercentAdvisor='';
			if(typeof(filter[i].PercentBanner ) == "undefined") filter[i].PercentBanner ='';
			if(typeof(filter[i].PercentChair  ) == "undefined") filter[i].PercentChair  ='';
			if(typeof(filter[i].PercentTable  ) == "undefined") filter[i].PercentTable  ='';
			if(typeof(filter[i].PercentWindow ) == "undefined") filter[i].PercentWindow ='';
			if(typeof(filter[i].PercentTrophy ) == "undefined") filter[i].PercentTrophy ='';	
			if(typeof(filter[i].PercentCandelabrum ) == "undefined") filter[i].PercentCandelabrum ='';	
		}
	}
}
function readColors (){
	var serverID = getServerId();
	s = GM_getValue ('Colors');
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts)
			Colors[k] = opts[k];
	}
}
function readUpgradeData (){
	var serverID = getServerId();
	s = GM_getValue ('UpgradeData_'+serverID);
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts){
			if (matTypeof(opts[k]) == 'object')
				for (kk in opts[k])
					upgradeData[k][kk] = opts[k][kk];
			else
				upgradeData[k] = opts[k];
		}
	}
}
function readCombatOptions (){
	var serverID = getServerId();
	s = GM_getValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID);
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts){
			if (matTypeof(opts[k]) == 'object')
				for (kk in opts[k])
					if (matTypeof(opts[k][kk]) == 'object')
						for (kkk in opts[k][kk])
							CombatOptions[k][kk][kkk] = opts[k][kk][kkk];
					else
						CombatOptions[k][kk] = opts[k][kk];
			else
				CombatOptions[k] = opts[k];
		}
	}
}
function readTrainingOptions(){
	var a=getServerId();
	s=GM_getValue("TrainingOptions_"+a);
	if(s!=null){
		opts=JSON2.parse(s);
		for(k in opts){
			TrainOptions[k]=opts[k]
		}
	}
}
function readCrestData (){
	var serverID = getServerId();
	s = GM_getValue ('CrestData_' + Seed.player['name'] + '_' +serverID);
	if (s != null) {
		opts = JSON2.parse (s);
		for (var i = 0; i < opts.length; i++) {
			CrestData[i] = new CrestFunc(opts[i]);
		}
	}
}
function readMarchOptions (){
  var serverID = getServerId();
  s = GM_getValue ('MarchOptions_' + Seed.player['name'] + '_' +serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
            if (matTypeof(opts[k][kk]) == 'object')
                for (kkk in opts[k][kk])
                  MarchOptions_[k][kk][kkk] = opts[k][kk][kkk];
            else
                MarchOptions[k][kk] = opts[k][kk];
      else
        MarchOptions[k] = opts[k];
    }
  }
}

function readApothecaryOptions (){
	var serverID = getServerId();
	s = GM_getValue ('ApothecaryOptions_'+Seed.player['name']+'_'+serverID, '[]');
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts){
			if (matTypeof(opts[k]) == 'object')
				for (kk in opts[k])
					ApothecaryOptions[k][kk] = opts[k][kk];
			else
				ApothecaryOptions[k] = opts[k];
		}
	}
}
function readTabOptions (){
	var serverID = getServerId();
	s = GM_getValue ('TabOptions_'+serverID);
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts){
			if (matTypeof(opts[k]) == 'object')
				for (kk in opts[k])
					TabOptions[k][kk] = opts[k][kk];
			else
				TabOptions[k] = opts[k];
		}
	}
}

function readDashboardOptions (){
  var serverID = getServerId();
  s = GM_getValue ('DashboardOptions_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          DashboardOptions[k][kk] = opts[k][kk];
      else
        DashboardOptions[k] = opts[k];
    }
  }
}
function readKsRange (){
  var serverID = getServerId();
  s = GM_getValue ('RCOptions_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          KsRange[k][kk] = opts[k][kk];
      else
        KsRange[k] = opts[k];
    }
  }
}


// BUTTONS
function createButton (label){var a=document.createElement('a'); a.innerHTML=' '+ label +'';return a;}	// a.className='button20';
function createBlinkButton (label){var a=document.createElement('a');a.className='button20';a.innerHTML=''+ label +'';return a;}
function makeButton20 (label){var a = document.createElement('a');a.className = "button20 ptButton20";var s = document.createElement('span');s.innerHTML = label;a.appendChild (s);return a;}
function strButton20 (label, tags){
	if (tags == null)
		tags = '';
	return ('<TABLE class=ptNoPad><TR><TD><A class="button20 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a></td></tr></table>' );
}
function strButton14 (label, tags){
	if (tags == null)
		tags = '';
	return ('<A class="button14 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a>' );
}
// function updatebotbutton2(a,b){var c=ById(b);if(c)c.innerHTML='<span style="color: #F71F02">'+a.replace("= "+culang.buttonON,butON).replace("= "+culang.buttonOFF,butOFF)+"</span>"}
// function updatebotbutton(a,b){var c=ById(b);if(c)c.innerHTML='<span style="color: #ff6">'+a.replace("= "+culang.buttonON,butON).replace("= "+culang.buttonOFF,butOFF)+"</span>"}
// function createRedButton(a,b){var c=document.createElement("a");c.style.display='none';c.style.background='none';c.id=b;c.innerHTML='<span style="color: #ff6">'+a+"</span>";return c}
// function createRedButton (a){var c=document.createElement('a');c.className='button20';c.innerHTML=' '+ a +' ';return c;}
function createRedButton(a,b){var c=document.createElement("a");c.style.display='none';c.id=b;c.innerHTML='<span style="color: #ff6">'+a+"</span>";return c}
// c.className="button20";
function createYellowButton(a,b){var c=document.createElement("a");c.className="button20";c.id=b;c.innerHTML='<span style="color: #ff6">'+a.replace("= "+culang.buttonON,butON).replace("= "+culang.buttonOFF,butOFF)+'</span>';return c}


// TAB MAINTABS
function AddMainTabLink(text, eventListener, mouseListener) {
	var a = createButton ("<IMG height='36' src='"+IMGbuttonPower+"'  alt='POWER' title='KoC Power - Main Tabs'>");
	a.className='tab';
	a.style.background='none';
	a.id = 'pdxTabs';
	var tabs=ById('main_engagement_tabs');

	if(!tabs) {
		tabs=ById('topnav_msg');
		if (tabs)
			tabs=tabs.parentNode;
	}
	if(tabs) {
		eNew2 = document.createElement('div');
		eNew2.id = 'ksQuick';
		eNew2.className='tabs_engagement';
		eNew2.style.padding='3px';
		eNew2.style.whiteSpace='nowrap';
		eNew2.style.width='745px';
		tabs.parentNode.insertBefore (eNew2, tabs);
		if (DashboardOptions.showMultiNote || Options.showKsBadge == false) {
		} else {
				eNew2.innerHTML="<span style='float:right;padding:5px;font-size:12px;text-shadow: 5px 2px 5px #FGFGFG; font-variant:small-caps; border-radius:18px 0px 18px 0px;  border: 1px inset none;background: url("+IMGksBG+");  -moz-box-shadow: 0px 0px 2px 2px #141516; color:#FFFFFF;'><center><b><a target='_blank' href='"+KsScriptPage+"' title='"+ScriptName+"'>"+ScriptName+"</a>: <a target='_blank' href='"+KsInstallLink+"' title='"+culang.ksInstallLatestNote+"'>"+Version+"</a></b></center></span>";
				//eNew2.innerHTML="<a id=KsSupportChat href='https://www.facebook.com/groups/mad.hatter.magic.elite/' style='float:right;margin-right:20px;' title='"+culang.ksSupportChat+"'><img src='"+IMGSupportLogo+"'></a><span style='float:right;padding:5px;font-size:12px;text-shadow: 5px 2px 5px #FGFGFG; font-variant:small-caps; border-radius:18px 0px 18px 0px;  border: 1px inset none;background: url("+IMGksBG+");  -moz-box-shadow: 0px 0px 2px 2px #141516; color:#FFFFFF;'><center><b><a target='_blank' href='"+KsScriptPage+"' title='"+ScriptName+"'>"+ScriptName+"</a>: <a target='_blank' href='"+KsInstallLink+"' title='"+culang.ksInstallLatestNote+"'>"+Version+"</a></b></center></span>";

		}
		//eNew2.innerHTML="<a id=KsSupportChat style='float:right;margin-right:20px;' title='"+culang.ksSupportChat+"'></a><span style='float:right;padding:5px;font-size:12px;text-shadow: 5px 2px 5px #FGFGFG; font-variant:small-caps; border-radius:18px 0px 18px 0px;  border: 1px inset none;background: url("+IMGksBG+");  -moz-box-shadow: 0px 0px 2px 2px #141516; color:#FFFFFF;'><center><b><a target='_blank' href='"+KsScriptPage+"' title='"+ScriptName+"'>"+ScriptName+"</a>: <a target='_blank' href='"+KsInstallLink+"' title='"+culang.ksInstallLatestNote+"'>"+Version+"</a></b></center></span>";

		var e = tabs.parentNode;
		var eNew = null;
		for (var i=0; i<e.childNodes.length; i++){
			var ee = e.childNodes[i];

			if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' &&  ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
				eNew = ee;
				break;
			}
		}
		if (eNew == null){
			eNew = document.createElement('div');
			eNew.className='tabs_engagement';
			eNew.style.padding='3px';
			tabs.parentNode.insertBefore (eNew, tabs);
			eNew.id = 'gmTabs';
			eNew.style.whiteSpace='nowrap';
			eNew.style.width='745px';
			eNew.style.height='20px';
			eNew.style.maxHeight='55px';
		}
		if (eNew2.firstChild){
			eNew2.insertBefore (a, eNew2.firstChild);
		}else{
			eNew2.appendChild(a);
		}


if (DashboardOptions.showMultiNote || Options.showKsBadge == false) {

		} else {
		/*
				ById("KsSupportChat").addEventListener('click',function() {
				window.open(homePage+"/support");
			}, false);
		*/
		}
		
		a.addEventListener('click',eventListener, false);
		if (mouseListener != null)
			a.addEventListener('mousedown',mouseListener, true);


		if (tabs) {
			GM_xmlhttpRequest({method:"GET",url:""+KsInstallLink+"",onload:function(a){var b=/\/\/\s*@version\s+(.+)\s*\n/i.exec(a.responseText);
				var c=Version;if(b){if(b[1]>c){
					var eNewMAJ=createBlinkButton ("<IMG height='32' src='"+IMGpdxTeam+"' title='"+culang.updateButtonNote+": "+b[1]+"'>"); 
					eNewMAJ.className='tab';
					eNewMAJ.style.background='none';
					eNewMAJ.id="pdxUpdate";
					eNewMAJ.title=culang.updateButtonNote;
					eNew2.insertBefore(eNewMAJ,eNew2.firstChild);
					eNewMAJ.addEventListener('click',function() {
						window.open(KsInstallLink);
					}, false);
					if (Options.postMultiUpdate) sendChat ("/a (update) - "+culang.updateButtonNote+" "+culang.mainVersion+": "+b[1]+"");
				}}},onerror:function(a){}})
		} 
		return a;
	}
	return null;
}
function AddMainTabLink2(text, eventListener, mouseListener) {
	var b = createButton ("<IMG height='36' src='"+IMGbuttonQuick+"'  alt='POWER' title='KoC Power - Quick Tabs'>");
		b.className='tab';
		b.style.background='none';
		b.id = 'pdxTabs2';

	var tabs=ById('main_engagement_tabs');
	if(!tabs) {
		tabs=ById('topnav_msg');
		if (tabs)
			tabs=tabs.parentNode;
	}
	if(tabs) {

		var e = tabs.parentNode;
		var eNew = null;
		for (var i=0; i<e.childNodes.length; i++){
			var ee = e.childNodes[i];

			if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' &&  ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
				eNew = ee;
				break;
			}
		}
		if (eNew == null){
			eNew = document.createElement('div');
			eNew.className='tabs_engagement';
			tabs.parentNode.insertBefore (eNew, tabs);
			eNew.id = 'gmTabs';
			eNew.style.whiteSpace='nowrap';
			eNew.style.width='745px';
		}
		if (eNew2.firstChild){
			eNew2.insertBefore (b, eNew2.firstChild);
		}else{
			eNew2.appendChild(b);
		}

		b.addEventListener('click',eventListener, false);
		if (mouseListener != null)
			b.addEventListener('mousedown',mouseListener, true);
		return b;
	}
	return null;
}
function AddSubTabLink(text, eventListener, id, type) {
	var a = createButton (text,'botbutton');
	a.className='tab';
	if (type=="none") a.style.backgroundImage ='none';

	a.id = 'pdxTabs2';

	var tabs=ById('main_engagement_tabs');
	if(!tabs) {
		tabs=ById('topnav_msg');
		if (tabs)
			tabs=tabs.parentNode;
	}
	if (tabs) {
		var e = tabs.parentNode;
		var gmTabs = null;
		for (var i=0; i<e.childNodes.length; i++){
			var ee = e.childNodes[i];
			if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs'   &&  ee.id!='ksSubTabs'){
				gmTabs = ee;
				break;
			}
		}
		if (gmTabs == null){
			gmTabs = document.createElement('div');
			gmTabs.className='ksSubTabs';
			tabs.parentNode.insertBefore (gmTabs, tabs);
			gmTabs.style.whiteSpace='nowrap';
			gmTabs.style.background='none';
			// gmTabs.style.position='absolute';
			// gmTabs.style.top='115px';
			// gmTabs.style.left='10px';
			// gmTabs.style.width='120px';
			gmTabs.lang = 'en_PB';
		}
		gmTabs.appendChild(a);
		a.addEventListener('click',eventListener, false);
		if (id != null)
			a.id = id;
		return a;
	}
	return null;
}

function AddTowerTab(text, eventListener, id) {
	var a = createButton (text,'botbutton');
	a.className='tabs_engagement';
	a.style.background='none';
	a.style.cssFloat="none";
	a.style.left="0px";
	a.style.height="50px";
	a.style.width="50px";
	a.style.zIndex = 999999;
	a.style.display = "none";
	//a.title="Attention !!! "+uW.g_js_strings.modaltitles.impatks+" !";
	var tabs=ById('main_engagement_tabs');
	if(!tabs) {
		tabs=ById('topnav_msg');
		if (tabs)
			tabs=tabs.parentNode;
	}
	if (tabs) {
		var e = tabs.parentNode;
		var gmTabs = null;
		for (var i=0; i<e.childNodes.length; i++){
			var ee = e.childNodes[i];
			if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
				gmTabs = ee;
				break;
			}
		}
		if (gmTabs == null){
			gmTabs = document.createElement('div');
			gmTabs.className='tabs_engagement';
			tabs.parentNode.insertBefore (gmTabs, tabs);
			gmTabs.style.whiteSpace='nowrap';
			gmTabs.style.width='745px';
			gmTabs.lang = 'en_PB';
		}
		gmTabs.appendChild(a);
		a.addEventListener('click',eventListener, false);
		if (id != null)
			a.id = id;
		return a;
	}
	return null;
}


// OTHER FUNCTIONS
uW.PTscout = function (x, y){
	var a=confirm(""+culang.scoutSendconfirm+"");
	if (a) {
		setTimeout (function (){
			ById('mapXCoor').value = x;
			ById('mapYCoor').value = y;
			uW.Modal.hideModalAll();
			uW.reCenterMapWithCoor();
			uW.changeview_map(ById('mod_views_map'));
			uW.modal_attack(3,x,y);
			setTimeout (function (){
				var scouter = ById('modal_attack_unit_ipt3');
				scouter.value=1;
				var evt = document.createEvent("KeyboardEvent");
				if(evt.initKeyboardEvent) {
					evt.initKeyboardEvent("keyup",true,true,null,false,false,false,false,0x10,0);
				} else {
					evt.initKeyEvent("keyup",true,true,null,false,false,false,false,0x10,0);
				}
				scouter.dispatchEvent(evt);
				uW.modal_attack_do();
			}, 500);
		}, 0);
	}
};
function cityStatusString (cs){
	if (cs==4)
		return 'Vacation';
	if (cs==3)
		return 'Truce';
	if (cs==2)
		return 'Beg Protection';
	return 'Normal';
}
function sendChat (msg){var m = ById("mod_comm_input");m.value = msg;uW.Chat.sendChat();}

function doDefTrain (cityId, siege, unitId, num, notify){
  var time = uW.modal_walls_traintime(unitId, num);
  var params = uW.Object.clone(uW.g_ajaxparams);
  params.cid = cityId;
  params.type = unitId;
  params.quant = num;
  params.items = siege;
  new MyAjaxRequest(uW.g_ajaxpath + "ajax/fortify.php" + uW.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok) {
          uW.seed.queue_fort["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, rslt.fortifyId]);
          if (notify != null)
            setTimeout (function (){notify(null);}, 500);
        } else {
          if (notify != null)
            setTimeout (function (){notify(rslt.errorMsg);}, 500);
        }
      },
      onFailure: function (rslt) {
        if (notify != null)
          notify(rslt.errorMsg);
      },
  });
}
function doTrain (cityId, tut, gam, unitId, num, notify){
	var time = uW.modal_barracks_traintime(unitId, num);
	if(tut==36){time=parseInt(time*0.7)}else{if(tut==37){time=parseInt(time*0.5)}else{if(tut==38){time=parseInt(time*0.3)}}}
	var params = uW.Object.clone(uW.g_ajaxparams);
	params.cid = cityId;
	params.type = unitId;
	params.quant = num;
	params.items = tut;
	params.gambleId = gam;
	new MyAjaxRequest(uW.g_ajaxpath + "ajax/train.php" + uW.g_ajaxsuffix, {
		method: "post",
		parameters: params,
		onSuccess: function(rslt) {
			if (rslt.ok) {
				var resourceFactors=[],resourceLost;
				if(gam!=null){time=rslt.timeNeeded;}
				for(var i=1;i<5;i++){
					if(rslt.gamble){resourceFactors.push(rslt.gamble[i.toString()]);}else{resourceFactors.push(1);}
					resourceLost=parseInt(uW.unitcost["unt"+unitId][i])*3600*parseInt(num);resourceLost=resourceLost*resourceFactors[i-1];
					uW.seed.resources["city"+cityId]["rec"+i][0]=parseInt(uW.seed.resources["city"+cityId]["rec"+i][0])-resourceLost;
				}
				uW.seed.citystats["city"+cityId].gold[0]=parseInt(uW.seed.citystats["city"+cityId].gold[0])-parseInt(uW.unitcost["unt"+unitId][5])*parseInt(num);
				uW.seed.citystats["city"+cityId].pop[0]=parseInt(uW.seed.citystats["city"+cityId].pop[0])-parseInt(uW.unitcost["unt"+unitId][6])*parseInt(num);
				if (parseInt(unitId) > 12 && parseInt(unitId) < 16) {
					uW.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null,true]);
				} else {
					uW.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null,false]);
				}
				if (parseInt(unitId) == 16) {
					Seed.items.i34001 = parseInt(Seed.items.i34001) - num;
					uW.ksoItems[34001].subtract(num);
				}
				if (tut!=0) {
					Seed.items["i"+tut]= parseInt(Seed.items["i"+tut]) - 1;
					uW.ksoItems[tut].subtract();
				}
				try {
				if(rslt.updateSeed) { uW.update_seed(rslt.updateSeed) }
				} catch (e) {}
				if (notify != null)
					setTimeout (function (){notify(null);}, 100);
			} else { if (notify != null){setTimeout (function (){notify(rslt.errorMsg);}, 100);} }
		},
		onFailure: function(rslt) {
			if (notify != null)
				notify(rslt.errorMsg);
		}
	});
}

function getAbsoluteOffsets (e){
	ret = {left:0, top:0};
	while (e.offsetParent){
		if (e.style.position == 'absolute')
			break;
		ret.left += e.offsetLeft;
		ret.top += e.offsetTop;
		e = e.offsetParent;
	}
	return ret;
}
function getClientCoords(e){
	if (e==null)
		return {x:null, y:null, width:null, height:null};
	var x=0, y=0;
	ret = {x:0, y:0, width:e.clientWidth, height:e.clientHeight};
	while (e.offsetParent != null){ret.x += e.offsetLeft;ret.y += e.offsetTop;e = e.offsetParent;}
	return ret;
}
function htmlTitleLine (msg){return '<TABLE width=100% cellspacing=0><TR><TD style="padding:0px" width=50%><HR></td><TD style="padding:0px">[ '+ msg +' ]</td><TD style="padding:0px" width=50%><HR></td></tr></table>';}
function objectName (o){var s = o.toString();return s.substr(7,s.length-8);}
function matTypeof (v){
	if (v == undefined)
		return 'undefined';
	if (typeof (v) == 'object'){
		if (!v)
			return 'null';
		else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
			return 'array';
		else return 'object';
	}
	return typeof (v);
}
// function matTypeof (v){//TODO replace duplicate
	// if (v == undefined)
		// return 'undefined';
	// if (typeof (v) == 'object'){
		// if (!v)
			// return 'null';
   // else if (uW.Object.prototype.toString.apply(v) === '[object Array]')
		// else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
			// return 'array';
		// else return 'object';
	// }
	// return typeof (v);
// };	
function addCommasInt(n){nStr = parseInt(n) + '';var rgx = /(\d+)(\d{3})/;while (rgx.test(nStr)) {nStr = nStr.replace(rgx, '$1' + THOUSANDS_SEP + '$2');}return nStr;}
function addCommas(nStr){nStr += '';x = nStr.split('.');x1 = x[0];x2 = x.length > 1 ? DEC_POINT + x[1] : '';var rgx = /(\d+)(\d{3})/;while (rgx.test(x1)) {x1 = x1.replace(rgx, '$1' + THOUSANDS_SEP + '$2');}return x1 + x2;}
function formatDate(Timestamp, FormatString) {
	FormatString = FormatString + "";

	UnixDate = new Date(Timestamp * 1000);
	var out = new Object();

	//Jahr
	out.y = UnixDate.getYear() - 100 + "";
	out.Y = "" + (out.y - 0 + 2000);

	//Monat
	out.n = UnixDate.getMonth() + 1;
	if (out.n > 9) {
		out.m = out.n;
	} else {
		out.m = '0' + out.n;
	}
	out.F = MONTH_NAMES[out.n - 1];
	out.M = MONTH_NAMES[out.n + 11];
	
	//Tag
	out.j = UnixDate.getDate();
	if (out.j > 9) {
		out.d = out.j;
	} else {
		out.d = '0' + out.j;
	}
	if (out.j == 1 || out.j == 21 || out.j == 31) {
		out.S = 'st';
	} else if (out.j == 2 || out.j == 22) {
		out.S = 'nd';
	} else if (out.j == 3 || out.j == 23) {
		out.S = 'rd';
	} else {
		out.S = 'th';
	}
	
	//Wochentag
	out.w = UnixDate.getDay();
	out.D = DAY_NAMES[out.w + 7];
	out.l = DAY_NAMES[out.w];
	
	//Stunden 24h
	out.G = UnixDate.getHours();
	if (out.G > 9) {
		out.H = out.G;
	} else {
		out.H = '0' + out.G;
	}
	
	//Stunden 12h
	if (out.G == 0) {
		out.g = 12;
	} else {
		if (out.G > 12) {
			out.g = out.G - 12;
		} else {
			out.g = out.G;
		}
	}
	if (out.g > 9) {
		out.h = out.g;
	} else {
		out.h = '0' + out.g;
	}
	
	//AM oder PM
	if (out.G > 11) {
		out.a = "pm";
		out.A = "PM";
	} else {
		out.a = "am";
		out.A = "AM";
	}
	
	//Minute
	var m = UnixDate.getMinutes();	
	if (m > 9) {
		out.i = m;
	} else {
		out.i = '0' + m;
	}
	
	//Sekunde
	var s = UnixDate.getSeconds();	
	if (s > 9) {
		out.s = s;
	} else {
		out.s = '0' + s;
	}
	//Formatierten String bauen
	var ret = '';
	var v = 0;
	var G = "";
	var f = "";
	while (v < FormatString.length) {
		G = FormatString.charAt(v);
		f = "";
		while ((FormatString.charAt(v) == G) && (v < FormatString.length)) {
			f += FormatString.charAt(v++);
		}
		if (out[f] != null) {
			ret = ret + out[f];
		} else {
			ret = ret + f;
		}
	}
	return ret;
}
function htmlSelector(a,b,c){m=[];m.push("<SELECT");if(c){m.push(" ");m.push(c)}for(k in a){m.push("><OPTION ");if(k==b)m.push("SELECTED ");m.push('value="');m.push(k);m.push('">');m.push(a[k]);m.push("</option>")}m.push("</select>");return m.join("")}
function unixTime(){ return parseInt (new Date().getTime() / 1000) + uW.g_timeoff;}
function timestrShort(a){a=parseInt(a);if(a>86400){var b=[];a/=3600;b.push(parseInt(a/24));b.push("d ");b.push(parseInt(a%24));b.push("h ");return b.join("")}else return timestr(a)}
function timestr(a,b){a=parseInt(a);var c=[];var d=a;if(d<61)return d+"s";if(d>86400){c.push(parseInt(d/86400));c.push("d ");d%=86400}if(d>3600||a>3600){c.push(parseInt(d/3600));c.push("h ");d%=3600}c.push(parseInt(d/60));c.push("m");if(b||a<=3600){c.push(" ");c.push(d%60);c.push("s")}return c.join("")}
function getMyAlliance(){if(Seed.allianceDiplomacies==null||Seed.allianceDiplomacies.allianceName==null)return[0,""+culang.mainNone+""];else return[Seed.allianceDiplomacies.allianceId,Seed.allianceDiplomacies.allianceName]}
function addCommasWhole(a){a+="";x=a.split(".");x1=x[0];x2=x.length>1?"."+x[1]:"";var b=/(\d+)(\d{3})/;while(b.test(x1)){x1=x1.replace(b,"$1"+","+"$2")}return x1}
function CmatSimpleSound (playerUrl, container, attrs, onLoad, flashVars) {
	var self = this;
	this.player = null;
	this.volume = 100;
	this.isLoaded = false;
	this.onSwfLoaded = null;
	var div = document.createElement ('div');
	this.onSwfLoaded = onLoad;
	if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
		div.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+playerUrl+'"><param name="quality" value="high"></object>';
		this.player = div.getElementsByTagName('object')[0];
	} else {
		div.innerHTML = '<embed src="'+playerUrl+'"  bgcolor="#eeeeee" allowfullscreen=false FlashVars="'+ flashVars +'" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" ></embed>';
		this.player = div.getElementsByTagName('embed')[0].wrappedJSObject;
	}
	if (container)
		container.appendChild (div);
	else
		document.body.appendChild (div);
	for (k in attrs)
		this.player.setAttribute(k, attrs[k]);

	this.setVolume = function (chanNum, vol) {
		if (!self.isLoaded)
			return;
		self.player.jsSetVolume(chanNum, vol);
		volume = vol;
	};

	this.load = function (chanNum, url, bStream, bAutoplay, bUsePolicyFile) {
		self.player.jsLoad(chanNum, url, bStream, bAutoplay, bUsePolicyFile);
	};

	this.play = function (chanNum, position) {
		if (this.isLoaded) {
			if (self.player.jsPlay)  self.player.jsPlay(chanNum, position);
		}
	};

	this.stop = function (chanNum) {
		if (!self.isLoaded)
			return;
		self.player.jsStop(chanNum);
	};

	this.getStatus = function (chanNum) {
		if (this.isLoaded)
			return self.player.jsGetStatus(chanNum);
	};

	this.debugFunc = function (msg) {	};

	this.swfDebug = function (msg) {self.debugFunc('SWF: ' + msg);};
	this.swfLoaded = function () {
		self.isLoaded = true;
		self.debugFunc('playerIsReady');
		if (self.onSwfLoaded)
			self.onSwfLoaded();
	};
	this.swfPlayComplete = function (chanNum) {	};
	this.swfLoadComplete = function (chanNum, isError){	}
}
function SliderBar (container, width, height, value, classPrefix, margin){
	var self = this;
	this.listener = null;
	if (value==null)
		value = 0;
	if (!margin)
		margin = parseInt(width*.05);
	this.value = value;
	if (width<20) width=20;
	if (height<5) height=5;
	if (classPrefix == null){
		classPrefix = 'slider';
		var noClass = true;
	}
	var sliderHeight = parseInt(height/2);
	var sliderTop = parseInt(height/4);
	this.sliderWidth = width - (margin*2);

	this.div = document.createElement ('div');
	this.div.style.height = height +'px';
	this.div.style.width = width +'px';
	this.div.className = classPrefix +'Cont';
	if (noClass)
		this.div.style.backgroundColor='#ddd';

	this.slider = document.createElement ('div');
	this.slider.setAttribute ('style', 'position:relative;');
	this.slider.style.height = sliderHeight + 'px';
	this.slider.style.top = sliderTop + 'px';
	this.slider.style.width = this.sliderWidth +'px';
	this.slider.style.left = margin +'px';
	this.slider.className = classPrefix +'Bar';
	this.slider.draggable = true;
	if (noClass)
		this.slider.style.backgroundColor='#fff';

	this.sliderL = document.createElement ('div');
	this.sliderL.setAttribute ('style', 'width:100px; height:100%; position:relative; ');
	this.sliderL.className = classPrefix +'Part';
	this.sliderL.draggable = true;
	if (noClass)
		this.sliderL.style.backgroundColor='#0c0';

	this.knob = document.createElement ('div');
	this.knob.setAttribute ('style', 'width:3px; position:relative; left:0px; background-color:#222');
	this.knob.style.height = height +'px';
	this.knob.style.top = (0-sliderTop) +'px';
	this.knob.className = classPrefix +'Knob';
	this.knob.draggable = true;
	this.slider.appendChild(this.sliderL);
	this.sliderL.appendChild (this.knob);
	this.div.appendChild (this.slider);
	container.appendChild (this.div);
	this.div.addEventListener('mousedown',  mouseDown, false);

	this.getValue = function () {return self.value;};

	this.setValue = function (val) {
		var relX = (val * self.sliderWidth);
		self.sliderL.style.width = relX + 'px';
		self.knob.style.left = relX + 'px';
		self.value = val;
		if (self.listener)
			self.listener(self.value);
	};

	this.setChangeListener = function (listener) {self.listener = listener;};

	function moveKnob (me){
		var relX = me.clientX - self.divLeft;
		if (relX < 0)
			relX = 0;
		if (relX > self.sliderWidth)
			relX = self.sliderWidth;
		self.knob.style.left = (relX - (self.knob.clientWidth/2) ) +'px';
		self.sliderL.style.width = relX + 'px';
		self.value =  relX / self.sliderWidth;
		if (self.listener)
			self.listener(self.value);
	}
	function doneMoving (){self.div.removeEventListener('mousemove', mouseMove, true);document.removeEventListener('mouseup', mouseUp, true);	}
	function mouseUp (me){moveKnob (me);doneMoving();}

	function mouseDown(me){
		var e = self.slider;
		self.divLeft = 0;
		while (e.offsetParent){
			self.divLeft += e.offsetLeft;
			e = e.offsetParent;
		}
		moveKnob (me);
		document.addEventListener('mouseup',  mouseUp, true);
		self.div.addEventListener('mousemove',  mouseMove, true);
	}
	function mouseMove(me){	moveKnob (me);}
}
function estETA(dist, unit, cityID, typemarche) {
	var ret={ETA:0,etaStr:culang.shortNotAvailable,friendETA:0,friendEtaStr:culang.shortNotAvailable};
	if (dist <= 0) return ret;
	var troop_type = unit;
	var horse=0;
	if(troop_type>6) horse=1;
	var troop_speed=parseInt(uW.unitstats["unt"+troop_type][3])*(1+0.1*parseInt(Seed.tech.tch11));
	if (horse){
		troop_speed=troop_speed*(1+0.05*parseInt(Seed.tech.tch12))
	}
	var Speed = troop_speed;


	var throne67=uW.cm.ThroneController.effectBonus(67);
	var throne68,throne69,throne70,throne71,throne72;throne68=throne69=throne70=throne71=throne72=0;
	if(typemarche==4){
		throne68 = uW.cm.ThroneController.effectBonus(68); // attaque
	}else{
		if(typemarche==3){ //eclaireur
			throne72=uW.cm.ThroneController.effectBonus(72)
		}else{
			if(typemarche==2){ //renforce
				throne69=uW.cm.ThroneController.effectBonus(69)
			}else{
				if(typemarche==5){ // reassign
					throne71=uW.cm.ThroneController.effectBonus(71)
				}else{
					if(typemarche==1){ // transport
						throne70=uW.cm.ThroneController.effectBonus(70)}}}}}

	var throneBoost=throne67+throne68+throne69+throne70+throne71+throne72;

	Speed=Speed*(1+(throneBoost*0.01));

	var gi=uW.cm.guardianModalModel.getMarchBonus();
	var multiplier=1+(gi*0.01);
	Speed=Speed*multiplier;
	var gSpeed = 0;
	var estSec;
	if (Speed>0) {
		gSpeed = Speed/6000;
		estSec = Math.ceil(parseFloat(dist)/gSpeed);
	}

	var e=1;
	if (ById("Ksitem_55")) {
		var l_elem=ById("Ksitem_55");
		if(l_elem&&l_elem.checked>0){ e=0.75;     }
	}
	if (ById("Ksitem_57")) {
		var l_elem=ById("Ksitem_57");
		if(l_elem&&l_elem.checked){   e=0.5;   }
	}
	ret.ETA = (parseInt((estSec*e+''))+30);
	if(Seed.playerEffects.returnExpire>uW.unixtime()){
		ret.ETA=parseInt(ret.ETA*0.5);
	}
	ret.etaStr = timestr (ret.ETA,1);
	if (cityID!=0) {
		var building = getCityBuilding (cityID, 18);
		if (building) {
			fSpeed = Speed * (1 + parseInt(building.maxLevel)/2);
			gSpeed = fSpeed/6000;
			estSec = (dist/gSpeed).toFixed(0);
			ret.friendETA = parseInt((estSec*e+''))+30;
			ret.friendEtaStr = timestr ((ret.friendETA+''),1);
		}
	} else {
		ret.friendETA = ret.ETA;
		ret.friendEtaStr = timestr ((ret.friendETA+''),1);
	}
	return ret;
}

/** Creates a recursive object dump
 *
 * @param {object} object the root object to dump.
 * @param {string} name of root object.
 * @return {string} string representation (dump) of object.
 */
function dump(object,rootName) {
	//GM_log("dump "+rootName);
	function dumpInternal(obj, path) {
		//GM_log("dumpInternal "+path);
		if(obj===null) {
			s += "" + path +": {null}" + "\n";
			return;
		} else if(obj===undefined){
			s += "" + path +": {undefined}" + "\n";
			return;
		}
		var valueType = typeof(obj);
		switch (valueType) {
			case "function": return;
			case "object"  : s+= "" + path +": {} -->" /*+ propValue.toString().substr(0,20)*/ + "\n";break;
			case "boolean" : s+= "" + path +": "+ obj.toString() + "\n";return;
			case "number"  : s+= "" + path +": "+ obj.toString() + "\n";return;
			case "string"  : s+= "" + path +": \""+ obj.toString() + "\"\n";return;
			default:s += "" + path +" ("+ valueType +"): "+ obj.toString() + "\n";return;
		}
		
		for (var o in objs) {
			if(o===obj) {
				s+= "{!Recursion stoped!}\n";
				return;
			} else objs.push(obj);
		}

		++ind;
		for (var propName in obj) dumpInternal(obj[propName], path+"."+propName);
		--ind;
	}
	var objs = [];
	var ind = 0;
	var s = "";
	if(typeof(rootName)=='undefined')rootName="*";
	dumpInternal(object,rootName);
	return s;
};
function Sound(file, callback) {
	var instance = this;
	instance.element = new Audio();
	instance.loaded = false;
	instance.err = false;
	instance.get = function(property) { return instance.element[property]; };
	instance.set = function(property, value) { 
		try {
			if (property == "volume" && value > 1) value = 1;
			if (property == "volume" && value < 0) value = 0;
			instance.element[property] = value;
		} catch (ex) {
			actionLog (culang.mainAudio,'Audio <b>set property</b> error: ' + property + ' = ' + value);
		}
	};
	instance.play = function() {
		if (instance.loaded && !instance.err) {
			instance.element.play();	
		} else {
			actionLog (culang.mainAudio,'Audio <b>play</b> error: Sound file not loaded<br>'+ file.substr(0,50));
		}
	};
	instance.pause = function() {
		instance.element.pause();
	};
	instance.stop = function() {
		if (instance.loaded && !instance.err) {
			instance.element.pause();
			instance.set('currentTime', 0);
		} else {
			actionLog (culang.mainAudio,'Audio <b>stop</b> error: Can\'t stop sound. Not loaded?<br>'+ file.substr(0,80));
		}
	};
	instance.load = function(file, callback) {
		instance.loaded = false;
		instance.err = false;
		var loadedHandler = function() {
			instance.loaded = true;
			instance.element.removeEventListener('canplaythrough', loadedHandler);
			if(callback) {
				callback.apply(instance);
			}
		};
		var errorHandler = function() {
			instance.loaded = false;
			instance.err = true;
			actionLog (culang.mainAudio,'Audio <b>load</b> error: Can\'t load soundfile.<br>'+ file.substr(0,80));
			instance.element.removeEventListener('error', errorHandler);		
			if(callback) {
				callback.apply(instance);
			}
		};
		instance.element.addEventListener('canplaythrough', loadedHandler);
		instance.element.addEventListener('error', errorHandler);
		instance.set('src', file);
		instance.element.load();
	};
	if(file) {
		instance.load(file, callback);
	}
}


//<editor-fold desc="SPLIT:CPopup.js">
function CPopup (prefix, x, y, width, height, enableDrag, onClose) {
	var pop = WinManager.get(prefix);
	if (pop){
		pop.show (false);
		return pop;
	}
	this.BASE_ZINDEX = 123457;
	this.stmaxh = height;
	this.stmaxw = width;
	this.show = show;
	this.toggleHide = toggleHide;
	this.getTopDiv = getTopDiv;
	this.getMainTopDiv = getMainTopDiv;
	this.getMainDiv = getMainDiv;
	this.getLayer = getLayer;
	this.setLayer = setLayer;
	this.setEnableDrag = setEnableDrag;
	this.getLocation = getLocation;
	this.setLocation = setLocation;
	this.focusMe = focusMe;
	this.isShown = isShown;
	this.unfocusMe = unfocusMe;
	this.centerMe = centerMe;
	this.destroy = destroy;
	this.autoHeight = autoHeight;
	this.autoWidth = autoWidth;
	this.div = document.createElement('div');
	this.prefix = prefix;
	this.onClose = onClose;
	var t = this;
	this.div.className = 'ksCPopup '+ prefix +'_CPopup';
	this.div.id = prefix +'_outer';
	this.div.style.background = "#fff";
	this.div.style.zIndex = this.BASE_ZINDEX;
	this.div.setAttribute("style", "padding:5px; display:none; resize: both; overflow-x:auto; min-width:150px; min-height:50px; border: 1px outset #141516; border-radius:"+Options.popupBorderRadius+"; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px #eee;");

	if (Options.KsTransparence) this.div.style.opacity = '0.9';
	this.div.style.width = width + 'px';
	// this.div.style.height = height + 'px';
	this.div.style.maxHeight = height + 'px';

	this.div.style.position = "absolute";
	this.div.style.top = y +'px';
	this.div.style.left = x + 'px';
	this.div.style.width = width + 'px';
	this.div.style.maxWidth = width + 'px';
	topClass = 'ksCPopupTop '+ prefix +'_CPopupTop';

	if (Options.pdxMenuLeft) {
		var m = '<TABLE cellspacing=0 width=100% height=100%><TR id="'+ prefix +'_bar" class="'+ topClass +'"><TD width=99% valign=bottom><img src="'+IMGKsTopLogo+'"><SPAN id="'+ prefix +'_top"></span></td><TD id='+ prefix +'_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'"><img style="margin-bottom:5px;" width=25px height=25px src="'+IMGcloseButton+'" title="'+culang.mainClose+'"></td></tr><TR><TD height=100% valign=top class="ksCPopMain '+ prefix +'_CPopMain" colspan=2 id="'+ prefix +'_main"></td></tr></table>';
	} else {
		var m = '<TABLE cellspacing=0 width=100% height=100%><TR id="'+ prefix +'_bar" class="'+ topClass +'"><TD width=99% valign=bottom><SPAN id="'+ prefix +'_top"></span></td><TD id='+ prefix +'_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'" style="padding:5px"><img style="margin-bottom:5px;" width=25px height=25px src="'+IMGcloseButton+'" title="'+culang.mainClose+'"></td></tr><TR><TD height=100% valign=top class="ksCPopMain '+ prefix +'_CPopMain" colspan=2 id="'+ prefix +'_main"></td></tr></table>';
	}
	document.body.appendChild(this.div);
	this.div.innerHTML = m;
	ById(prefix+'_X').addEventListener ('click', e_XClose, false);
	this.dragger = new CWinDrag (ById(prefix+'_bar'), this.div, enableDrag);

	this.div.addEventListener ('mousedown', e_divClicked, false);
	WinManager.add(prefix, this);

	function e_divClicked (){t.focusMe();}
	function e_XClose (){
		t.show(false);
		if (t.onClose != null)
			t.onClose();
	}
	function autoHeight (onoff){if (onoff) {t.div.style.height = '';t.div.style.maxHeight ='';}else{t.div.style.height = t.stmaxh;t.div.style.maxHeight = t.stmaxh;}}
	function autoWidth (onoff){if (onoff) {t.div.style.width = '';t.div.style.maxWidth ='';}else{t.div.style.width = t.stmaxw;t.div.style.maxWidth = t.stmaxw;}}
	function focusMe (){
		t.setLayer(5);
		for (k in uW.cpopupWins){
			if (k != t.prefix)
				uW.cpopupWins[k].unfocusMe();
		}
	}
	function unfocusMe (){t.setLayer(-5);	}
	function getLocation (){return {x: parseInt(this.div.style.left), y: parseInt(this.div.style.top)};}
	function setLocation (loc){t.div.style.left = loc.x +'px';t.div.style.top = loc.y +'px';}
	function destroy (){document.body.removeChild(t.div);WinManager.delete (t.prefix);}
	function centerMe (parent){
		if (parent == null){
			var coords = getClientCoords(document.body);
		} else
			var coords = getClientCoords(parent);
		var x = ((coords.width - parseInt(t.div.style.width)) / 2) + coords.x;
		var y = ((coords.height - parseInt(t.div.style.height)) / 2) + coords.y;
		if (x<0)
			x = 0;
		if (y<0)
			y = 0;
		t.div.style.left = x +'px';
		t.div.style.top = y +'px';
	}
	function setEnableDrag (tf){t.dragger.setEnable(tf);}
	function setLayer(zi){t.div.style.zIndex = ''+ (this.BASE_ZINDEX + zi);}
	function getLayer(){return parseInt(t.div.style.zIndex) - this.BASE_ZINDEX;}
	function getTopDiv(){return ById(this.prefix+'_top');}
	function getMainDiv(){return ById(this.prefix+'_main');}
	function getMainTopDiv(){return ById(this.prefix+'_top');}
	function isShown (){return t.div.style.display == 'block';}
	function show(tf){if (tf){t.div.style.display = 'block';t.focusMe ();} else {t.div.style.display = 'none';}return tf;}
	function toggleHide(t){if (t.div.style.display == 'block') {return t.show (false);} else {return t.show (true);}}
}
//</editor-fold>


//<editor-fold desc="SPLIT:CWinDrag.js">
function CWinDrag (clickableElement, movingDiv, enabled) {
	var t=this;
	this.setEnable = setEnable;
	this.setBoundRect = setBoundRect;
	this.debug = debug;
	this.dispEvent = dispEvent;
	this.lastX = null;
	this.lastY = null;
	this.enabled = true;
	this.moving = false;
	this.theDiv = movingDiv;
	this.body = document.body;
	this.ce = clickableElement;
	this.moveHandler = new CeventMove(this).handler;
	this.outHandler = new CeventOut(this).handler;
	this.upHandler = new CeventUp(this).handler;
	this.downHandler = new CeventDown(this).handler;
	this.clickableRect = null;
	this.boundRect = null;
	this.bounds = null;
	this.enabled = false;
	if (enabled == null)
		enabled = true;
	this.setEnable (enabled);

	function setBoundRect (b){this.boundRect = boundRect;this.bounds = null;}
	function setEnable (enable){
		if (enable == t.enabled)
			return;
		if (enable){
			clickableElement.addEventListener('mousedown',  t.downHandler, false);
			t.body.addEventListener('mouseup', t.upHandler, false);
		} else {
			clickableElement.removeEventListener('mousedown', t.downHandler, false);
			t.body.removeEventListener('mouseup', t.upHandler, false);
		}
		t.enabled = enable;
	}

	function CeventDown (that){
		this.handler = handler;
		var t = that;
		function handler (me){
			if (t.bounds == null){
				t.clickableRect = getClientCoords(clickableElement);
				t.bodyRect = getClientCoords(document.body);
				if (t.boundRect == null)
					t.boundRect = t.clickableRect;
				t.bounds = {top:10-t.clickableRect.height, bot:t.bodyRect.height-25, left:40-t.clickableRect.width, right:t.bodyRect.width-25};
			}
			if (me.button==0 && t.enabled){
				t.body.addEventListener('mousemove', t.moveHandler, true);
				t.body.addEventListener('mouseout', t.outHandler, true);
				t.lastX = me.clientX;
				t.lastY = me.clientY;
				t.moving = true;
			}
		}
	}

	function CeventUp  (that){
		this.handler = handler;
		var t = that;
		function handler (me){
			if (me.button==0 && t.moving)
				_doneMoving(t);
		}
	}

	function _doneMoving (t){
		t.body.removeEventListener('mousemove', t.moveHandler, true);
		t.body.removeEventListener('mouseout', t.outHandler, true);
		t.moving = false;
	}

	function CeventOut  (that){
		this.handler = handler;
		var t = that;
		function handler (me){
			if (me.button==0){
				t.moveHandler (me);
			}
		}
	}

	function CeventMove (that){
		this.handler = handler;
		var t = that;
		function handler (me){
			if (t.enabled && !t.wentOut){
				var newTop = parseInt(t.theDiv.style.top) + me.clientY - t.lastY;
				var newLeft = parseInt(t.theDiv.style.left) + me.clientX - t.lastX;
				if (newTop < t.bounds.top){     // if out-of-bounds...
					newTop = t.bounds.top;
					_doneMoving(t);
				} else if (newLeft < t.bounds.left){
					newLeft = t.bounds.left;
					_doneMoving(t);
				} else if (newLeft > t.bounds.right){
					newLeft = t.bounds.right;
					_doneMoving(t);
				} else if (newTop > t.bounds.bot){
					newTop = t.bounds.bot;
					_doneMoving(t);
				}
				t.theDiv.style.top = newTop + 'px';
				t.theDiv.style.left = newLeft + 'px';
				t.lastX = me.clientX;
				t.lastY = me.clientY;
			}
		}
	}

	function debug  (msg, e){
		logit ("*************** "+ msg +" ****************");
		logit ('clientWidth, Height: '+ e.clientWidth +','+ e.clientHeight);
		logit ('offsetLeft, Top, Width, Height (parent): '+ e.offsetLeft +','+ e.offsetTop +','+ e.offsetWidth +','+ e.offsetHeight +' ('+ e.offsetParent +')');
		logit ('scrollLeft, Top, Width, Height: '+ e.scrollLeft +','+ e.scrollTop +','+ e.scrollWidth +','+ e.scrollHeight);
	}

	function dispEvent (msg, me){
		logit (msg + ' Button:'+ me.button +' Screen:'+ me.screenX +','+ me.screenY +' client:'+  me.clientX +','+ me.clientY +' rTarget: '+ me.relatedTarget);
	}
}
//</editor-fold>

//END GLOBAL FUNCTION
//</editor-fold>

pdxStartup ();


//<editor-fold desc="SPLIT:KSXbuttler.js">
//	
//	   KOC POWER - KSX BUTTLER											        
//	


if (Options.enableButtler) {eval(GM_getResourceText("PLUGIN_BUTTLER")); } else {}
function readLangOptions (){
	s = GM_getValue ('LangOptions_');
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts){
			if (matTypeof(opts[k]) == 'object')
				for (kk in opts[k])
					LangOptions[k][kk] = opts[k][kk];
			else
				LangOptions[k] = opts[k];
		}
	}
};
function getThroneItemName(itemId){
	// Selten table von Courage +2
	var item=uW.kocThroneItems[itemId];
	var name = item.createName();
	if (name.indexOf('+') < 0) name = name + ' +' + item.level;
	return name;
}
//</editor-fold>


//<editor-fold desc="SPLIT:demistStuff.js">
//	
//	   DEMIST															        
//	


function demist() {


   var uW = unsafeWindow;
   var CM = uW.cm;
   var Seed = uW.seed;
   
  
   // add a new option to the context menu
   uW.cm.ContextMenuMapController.prototype.MapContextMenus.City["5"].push("abcd");

   // add actions to the menu item
   var mod = new CalterUwFunc('cm.ContextMenuMapController.prototype.calcButtonInfo',
         [['default:', 'case "abcd":' +
           '  b.text = "X-ray Vision"; b.color = "green"; ' +
           '  b.action = function () { ' +
           '    fetch_bm(e.tile.id,  e.tile.x, e.tile.y); ' +
           '  }; ' +
           '  d.push(b); break; ' +
           ' default: ']]);

   mod.setEnable(true);

   // 
   uW.fetch_bm = function(tileId, tileX, tileY) {
      // add bookmark
      var params = uW.Object.clone(uW.g_ajaxparams);
      params.requestType = "BOOKMARK_LOCATION";
      params.tileId = tileId;
      params.bookmarkName = "City(" + tileX + ", " + tileY + ")";
      new uW.Ajax.Request(uW.g_ajaxpath + "ajax/tileBookmark.php" + uW.g_ajaxsuffix, {
         method: "post",
         parameters: params,
         onSuccess: function (message) {
            var rslt = eval("(" + message.responseText + ")");

            if (rslt.ok) {

               // fetch data
               fetch(tileX, tileY);
            }

            if (!rslt.ok) {
               fetch(tileX, tileY);
            }
         },
      });
   }
};
//remove the bookmark
function removeBM(id1) {
   var uW = unsafeWindow;

   var id = id1.split("a")[1];
   var params = uW.Object.clone(uW.g_ajaxparams);
   params.requestType = "REMOVE_BOOKMARK";
   params.bookmarkId = id;
   new uW.Ajax.Request(uW.g_ajaxpath + "ajax/tileBookmark.php" + uW.g_ajaxsuffix, {
      method: "post",
      parameters: params,
   });
};
//get bookmark info
function fetch (tileX, tileY) {
   var uW = unsafeWindow;
   var CM = uW.cm;
   var Seed = uW.seed;
   var params = uW.Object.clone(uW.g_ajaxparams);
   params.requestType = "GET_BOOKMARK_INFO";
   new uW.Ajax.Request(uW.g_ajaxpath + "ajax/tileBookmark.php" + uW.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (message) {

         var cb = function (rslt, bookmark) {
            // handle the results
            
            if (!rslt.ok){
               return;
            }
            
            var u = rslt.userInfo[0];

            var a = ''+culang.mainNone+'';
            if (u.allianceName)
               a = u.allianceName +' ('+ getDiplomacy(u.allianceId) + ')';
            
            var status = "";
            switch (parseInt(bookmark.cityStatus)) {
               case 1:
                   status = uW.g_js_strings.commonstr.normal;
                   break;
               case 2:
                   status = uW.g_js_strings.MapObject.begprotect;
                   break;
               case 3:
                   status = uW.g_js_strings.commonstr.truce;
                   break;
               case 4:
                   status = uW.g_js_strings.commonstr.vacation;
                   break;
               default:
                   status = uW.g_js_strings.commonstr.normal;
           }
            
            var n = '<div> <b>'+culang.mainName+':</b> ' + u.genderAndName + '<br/><b>'+uW.g_js_strings.commonstr.might+':</b> ' + addCommas(u.might) +
                '<br/><b>' + uW.g_js_strings.commonstr.alliance+':</b> '+ a +
                '<br/><b>Location:</b> ' + bookmark.xCoord + ',' + bookmark.yCoord +
                '<br/><b>'+culang.searchResultsCityName+':</b> ' + bookmark.cityName + 
                '<br/><b>'+culang.mainStatus+':</b> ' + status + 
                "</div>";
                
                uW.Modal.showAlert(n);
         };

         var rslt = eval("(" + message.responseText + ")");

         if (rslt.ok) {
            var bookmarkInfo = rslt.bookmarkInfo;
            for (id in bookmarkInfo) {
               var bm = bookmarkInfo[id];
               if ( (bm.xCoord == tileX) && (bm.yCoord == tileY)) {
                  if (bm.tileCItyId == null || bm.tileCItyId == 0) {
                     uW.Modal.showAlert("<div>There is no longer a city at this location</div>");
                  }
                  else
                  {
                     fetchPlayerInfo (bm.tileUserId, function (r) {cb(r,bm);});
                  }
                  removeBM(id);
               }
            }
         }
         if (!rslt.ok) {
         }
      },
      onFailure: function () {}
   });
   
};
function fetchPlayerInfo(uid, notify){
   var uW = unsafeWindow;
   var CM = uW.cm;
   var Seed = uW.seed;
   var params = uW.Object.clone(uW.g_ajaxparams);
   params.uid = uid;
   new uW.Ajax.Request(uW.g_ajaxpath + "ajax/getUserGeneralInfo.php" + uW.g_ajaxsuffix, {
     method: "post",
     parameters: params,
     onSuccess: function (rslt) {
       notify (eval("(" + rslt.responseText + ")"));
     },
     onFailure: function (rslt) {
       notify ({errorMsg:'AJAX error'});
     },
   });
};
//</editor-fold>


//<editor-fold desc="SPLIT:debug.js">
//	
//	   DEBUG															        
//	


var debugWin = {
  popDebug : null,
  dbDefaultNot : '',
  dbSelect : {},

  doit : function (){ 
    var t = debugWin;    

    function syncBoxes (){
      var div = document.getElementById('dbpoplist');
      for (var i=0; i<div.childNodes.length; i++){
        if (div.childNodes[i].type && div.childNodes[i].type=='checkbox'){
          var name=div.childNodes[i].name.substr(6);
          div.childNodes[i].checked = t.dbSelect[name];
        }
      } 
    }
    function clickedAll (){
      for (var k in t.dbSelect)
        t.dbSelect[k] = true;
      syncBoxes();
    }
    function clickedNone (){
      for (var k in t.dbSelect)
        t.dbSelect[k] = false;
      syncBoxes();
    }
    function clickedDefaults (){
      for (k in t.dbSelect)
        t.dbSelect[k] = false;
      var not = t.dbDefaultNot.split(',');
      for (var i=0; i<not.length; i++)
        t.dbSelect[not[i]] = false;
      syncBoxes();
    }
    function clickedShow (){
      var now = new Date();
      var myseed = uW.Object.clone (Seed);
      var div = document.getElementById('dbpoplist');
      for (var i=0; i<div.childNodes.length; i++){
        if (div.childNodes[i].type && div.childNodes[i].type=='checkbox'){
          var name=div.childNodes[i].name.substr(6);
          if (!div.childNodes[i].checked)
            delete myseed[name];
        }
      } 
      WinLog.write ("seed @ "+ unixTime()  +" ("+ now +")\n\n"+ inspect (myseed, 8, 1));
      myseed=null;
    }
    
    function clickedShowScripts (){
      var scripts = document.getElementsByTagName('script');
      for (var i=0; i<scripts.length; i++){
        if (scripts[i].src!=null && scripts[i].src!='')
          WinLog.write ('<A style="color:black; text-decoration:underline;" TARGET=_tab HREF="'+ scripts[i].src +'">'+ scripts[i].src +'</a>');
      }
    }
    
    if (t.popDebug == null){  
      t.popDebug = new CPopup ('db', 0, 0, 600,500, true);
      t.popDebug.getTopDiv().innerHTML = '<div class="popupBanner">DEBUG</div>';
      t.popDebug.getMainDiv().innerHTML = '<DIV><INPUT type=submit id=dbsuball value=ALL> &nbsp; <INPUT type=submit id=dbsubnone value=NONE> &nbsp; \
        <INPUT type=submit id=dbdefaults value=DEFAULTS> &nbsp; <INPUT type=submit id=dbsubdo value=SHOW> &nbsp; <INPUT type=submit id=dbsubscripts value=SCRIPTS></div>\
        <DIV id=dbpoplist style="max-height:400px; height:400px; overflow-y:auto"></div>';
      var div = document.getElementById('dbpoplist');
      for (var k in Seed)
        t.dbSelect[k] = false;
      var not = t.dbDefaultNot.split(',');
      for (var i=0; i<not.length; i++)
        t.dbSelect[not[i]] = false;
      var m = [];
      for (k in t.dbSelect){
        m.push ('<INPUT type=checkbox ');
        m.push ('name="dbpop_');
        m.push (k);
        m.push ('"> &nbsp; ');
        m.push (k);
        m.push ('<BR>');
      }
      div.innerHTML = m.join ('');
      document.getElementById('dbsuball').addEventListener('click', clickedAll, false);
      document.getElementById('dbsubnone').addEventListener('click', clickedNone, false);
      document.getElementById('dbdefaults').addEventListener('click', clickedDefaults, false);
      document.getElementById('dbsubdo').addEventListener('click', clickedShow, false);
      document.getElementById('dbsubscripts').addEventListener('click', clickedShowScripts, false);
      syncBoxes();
    }
    t.popDebug.show (true);
  },
}
var WINLOG_MAX_ENTRIES = 1000;     // TODO
var WinLog = {
  state : null,
  win: null,
  eOut : null,
  lastE : null,
  enabled : true,
  reverse : true,
  busy : false,
	isOpening : false,

  open : function (){
    var t = WinLog;

    function eventButClear(){
      var t = WinLog;
      t.lastE = null;
      t.eOut.innerHTML ='';
    }
    function eventButReverse(){
      var t = WinLog;
      if (t.busy)
        return;
      t.busy = true;
      if (t.reverse){
        t.win.document.getElementById('wlRev').value= 'Top';
        t.reverse = false;
      } else{
        t.win.document.getElementById('wlRev').value= 'Bottom';
        t.reverse = true;
      }
      var n = t.eOut.childNodes.length;
      if (n < 2)
        return;
      for (i=n-2; i>=0; i--){
        t.eOut.appendChild (t.eOut.childNodes[i]);
      }
      t.busy = false;
    }
    
    if (!t.win || t.win.closed){
			t.isOpening = true;  
			// Firefox bug??? It appears as if a new thread is started on open, withOUT reusing same window
			//t.win = window.open('', 'uwtrace', 'top=30,left=0,width=900,height=700,scrollbars=no,location=no,menubar=no,directories=no,status=no');
			t.win = new CPopup('ptwinlog', 0, 0, 600, 800, true, function(){t.win.destroy(); t.win=null; t.win.closed=true;});
			t.win.show(true);
			t.isOpening = false; 
			t.state = null; 
    }
    
    if (t.state == null){
		
      t.win.getMainDiv().innerHTML = '<STYLE>pre{margin:0px} hr{margin:3px; height:1px; border:0px; color:#cee; background-color:#cee}</style>\
        <BODY style="margin:0px; padding:0px; border:none">\
        <DIV id=winlogtop style="background-color:#d0d0d0; margin:0px; padding:0px; border:1px solid">\
        <INPUT id=wlClear type=submit value="Clear"> &nbsp; <INPUT id=wlRev type=submit value="Bottom"></div>\
        <DIV id=wlOut style="overflow-y:auto; overflow-x:auto; max-height:800px; width:600px"></div></body>';
      t.win.getTopDiv().innerHTML = '<div class="popupBanner"><b class="topInfo">Info</b></div>';
			document.getElementById('wlClear').addEventListener('click', eventButClear, false);
      document.getElementById('wlRev').addEventListener('click', eventButReverse, false);
      t.eOut =  document.getElementById('wlOut');
      t.lastE = null;
      t.state = 1;
    }
  },

  writeText : function (msg){
    WinLog.write (msg.htmlEntities()); 
  },
  
  write : function (msg){
    var t = WinLog;
    if (!t.enabled || t.isOpening)
      return;
    t.open();
    var te = document.createElement('pre');
    var now = new Date();
    var m = [];
    var millis = now.getMilliseconds();
    m.push (now.toTimeString().substring (0,8));
    m.push ('.');
    if (millis<100)
      m.push('0');
    if (millis<10)
      m.push('0');
    m.push(millis);
    m.push (': ');
    m.push (msg);
    te.innerHTML = m.join('');

    if (t.reverse){
      if (t.lastE == null){
        t.eOut.appendChild(te);
        t.lastE = te;
      } else {
        t.eOut.insertBefore(te, t.lastE);
      }
      var hr = document.createElement('hr');
      t.eOut.insertBefore(hr, te);
      t.lastE = hr;
    } else {
      t.eOut.appendChild(te);
      t.eOut.appendChild(document.createElement('hr'));
    }
  },
};
//</editor-fold>


//<editor-fold desc="SPLIT:Tabs/MercenaryCamps.js">
/************************************************************************************
 *						KOC POWER - TABS MERCENARY CAMPS								*
 ************************************************************************************/
Tabs.MercenaryCamps = {
	tabLabel: culang.OldmainDarkForestLabel,
	tabOrder : TabOptions.toDarkForestOld,
	tabDisabled : false,
	myDiv : null,
	MapAjax : new CMapAjax(),
	koordlist: [],
	popFirst : true,
	opt : {},
	nextattack : null,
	searchRunning : false,
	tilesSearched : 0,
	tilesFound : 0,
	curX : 0,
	curY : 0,
	lastX : 0,
	firstX : 0,
	firstY : 0,
	lastY : 0,
	rallypointlevel:0,
	knt:{},
	barbArray:{},
	lookup:1,
	city:0,
	deleting:false,


		init : function (div){
		var t = Tabs.MercenaryCamps;
		t.myDiv = div;
		readAttackOptions();
		if (AttackOptions.MaxDistance > 75) AttackOptions.MaxDistance = 75;
		var m = '<DIV id=pbDarkForestTab2 class=pdxStat>'+culang.OlddfHead+' - <input type=button value="?" id=boaideautofo2 class=buttonHelp></div><TABLE id=pbDarkForestOptions2 width=100% height=0% class=pdxTab><TR align="center">';
		if (Options.AttackRunning == false) {
			m += '<TD><INPUT id=AttSearch2 type=submit value="'+culang.OldmainDarkForest+' = '+culang.OldbuttonOFF+'"></td>';
		} else {
			m += '<TD><INPUT id=AttSearch2 type=submit value="'+culang.OldmainDarkForest+' = '+culang.OldbuttonON+'"></td>';
		}
		m += '<TD><INPUT id=troopselect2 type=submit value="'+culang.OlddfSelectTroops+'"></td>';
		m += '<TD><INPUT id=Options2 type=submit value="'+culang.OldtabLabelOptions+'"></td>';
		m += '</tr></table></div>';

		m += '<DIV id=pbTraderDivD2 class=pdxStat>'+culang.OlddfStatusHead+'</div>';

		m += '<TABLE id=pbbarbstats2 width=100% height=0% class=pdxTab><TR align="left"><TR>';
		for(i=0;i<Seed.cities.length;i++){
			m += '<TD>' + Seed.cities[i][1] +'</td>';
		}
		m+='</tr><TR>';
		for(i=0;i<Seed.cities.length;i++){
			m += '<TD><DIV><span id='+ 'pdtotalcity' + i +'></span></div></td>';
		}
		m+='</tr><TR>';
		for(i=0;i<Seed.cities.length;i++){
			m += '<TD><DIV><span id='+ 'pddatacity' + i +'></span></div></td>';
		}
		m+='</tr><TR>'
		for(i=0;i<Seed.cities.length;i++){
			m += '<TD><DIV><span id='+ 'pddataarray' + i +'></span></div></td>';
		}
		m+='</tr></table><TABLE id=pbbarbstats width=100% height=0% class=pdxTab><TR align="center"><TR>';
		for (i=0;i<=7;i++) {
			m+='<TD><DIV><span id='+ 'pberror' + i +'></span></div></td>';
		}
		m+='</tr></table>';
		m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.OlddfSettingsHead+'</div>';
		m += '<TABLE width=100% height=0% class=pdxTab><TR align="center">';
		for(i=0;i<Seed.cities.length;i++){
			m += '<TR><TD>' + Seed.cities[i][1] +'</td>';
			for (w=1;w<=10;w++){
				m += '<TD class=pblevelopt2><INPUT id=pbcity2_'+i+'level'+w+' type=checkbox unchecked=true>'+culang.OldshortLevel+': '+w+'</td>';
			}
		}

		t.myDiv.innerHTML = m;

		saveAttackOptions();
		t.checkBarbData();

		for(i=0;i<Seed.cities.length;i++){
			var element = 'pdtotalcity'+i;
			if (t.barbArray[i+1] == undefined) ById(element).innerHTML = '<i>'+culang.OlddfNoData+'</i>';
			else ById(element).innerHTML =  ''+culang.OlddfShort+': ' + t.barbArray[i+1].length;
		}

		for(i=0;i<Seed.cities.length;i++){
			for (w=1;w<=10;w++){
				ById('pbcity2_'+i+'level'+w).checked = AttackOptions.Levels[i+1][w];
			}
		}

		ById('AttSearch2').addEventListener('click', function(){t.toggleBarbState(this)} , false);

		ById('boaideautofo2').addEventListener('click', function(){
			window.open(homePage+" ");
		} , false);

		ById('Options2').addEventListener('click', t.barbOptions , false);
		ById('troopselect2').addEventListener('click', t.troopOptions , false);
		var element_class = document.getElementsByClassName('pblevelopt2');
		for (k=0;k<element_class.length;k++){
			element_class[k].addEventListener('click', t.saveLevelOptions , false);
		}
	},

	saveLevelOptions : function(){
		for(i=0;i<Seed.cities.length;i++){
			AttackOptions.Levels[i+1][0]=false;
			for (w=1;w<=10;w++){
				var ele = ById('pbcity2_'+i+'level'+w);
				AttackOptions.Levels[i+1][w]=ele.checked;
				if (ele.checked)
					AttackOptions.Levels[i+1][0]=true;
			}
		}
		saveAttackOptions();
	},

	troopOptions: function(){
		var t = Tabs.MercenaryCamps;
		var troopDef = [ [culang.shrsupply, 1],[culang.shrmilitiaman, 2],[culang.scout, 3],[culang.shrpikeman, 4],[culang.shrswordsman, 5],[culang.shrtarcher, 6],[culang.shrcavalry, 7],[culang.shrheavycavalry, 8],[culang.shrsupplywagon, 9],[culang.shrballista, 10],[culang.shrbatteringram, 11],[culang.shrcatapult, 12],[culang.shrbloodthorn, 13] ,[culang.shrexec, 14],[culang.shrswall, 15],[culang.shrflarcher, 16]]; 

		if(t.troopselect == null)
			t.troopselect = new CPopup ('pbtroopselect', 0, 0, 1000, 445, true, function(){t.saveTroops();});
		t.troopselect.centerMe (mainPop.getMainDiv());
		var z= '<TABLE width=100%><TR>';
		z+='<TD></td>';
		for(var i=0; i<troopDef.length; i++)
			z+='<TD style="text-align:center;"><img title="'+uW.unitcost['unt'+(i+1)][0]+'" src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+(i+1)+'_50.jpg></td>';
		z+='</tr>';
		for(i=0;i<10;i++){
			z += '<TR><TD>'+culang.OlddfTroopSelectLvl+' '+(i+1)+': </td>';
			for(var j=0; j<troopDef.length; j++){
				z += '<TD style="text-align:center;"><INPUT id="level'+i+'troop'+j+'" type=text size=5 maxlength=6 value="'+AttackOptions.Troops[i+1][j+1]+'" /></td>';
			}
			z+='</tr>';
		}
		z+='</table><sup><span class=boldRed><u>'+culang.mainImportant+'</u></span>:</sup> <span class=helpText>'+ culang.dfHeadDFTroopsNote+'</span>';
		t.troopselect.getMainDiv().innerHTML = z;
		t.troopselect.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.OlddfTroopSelectHead+'</div>';
		t.troopselect.show(true);
	},

	barbOptions: function(){
		var t = Tabs.MercenaryCamps;
		if(t.barboptions == null)
			t.barboptions = new CPopup ('pbbarboptions', 0,0, 375,350, true);
		t.barboptions.centerMe (mainPop.getMainDiv());
		t.barboptions.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.OlddfPopupHead+' '+getServerId()+'</div>';
		var y = '<DIV style="max-height:400px; overflow-y:auto;"><DIV class=pdxStat>'+culang.OlddfPopupHeadReset+'</div><TABLE width=100%>';
		y +='<TR><TD style="margin-top:5px; text-align:center;"><INPUT id=pbresetbarbs type=submit value="'+culang.mainReset+'"></td>';
		y +='<TD style="margin-top:5px; text-align:center;"><INPUT id=pbpaintbarbs type=submit value="'+culang.mainShow+'"></td>';
		y += '<TD><SELECT id=pbcity type=list></td></tr></table>';
		y +='<TD style="margin-top:5px; text-align:center;"><DIV class=pdxStat> '+culang.tabLabelOptions+' </div></td><TABLE>';
		y +='<TR><TD>'+culang.mainIntervall+': <INPUT id=pbsendint type=text size=4 maxlength=4 value='+ AttackOptions.SendInterval +' \> '+culang.mainSeconds+'</td></tr>';
		y +='<TR><TD>'+culang.OlddfMaxSearchDistance+': <INPUT id=pbmaxdist type=text size=4 maxlength=4 value='+ AttackOptions.MaxDistance +' \></td></tr>';
		y +='<TR><TD>'+culang.OlddfRallyClip+' <INPUT id=rallyclip type=text size=1 maxlength=2 value="'+AttackOptions.RallyClip+'" \> '+culang.OlddfRallyClip2+'</td></tr>';
		y +='<TR><TD><INPUT id=pbreport type=checkbox '+(AttackOptions.UpdateEnabled?'CHECKED':'')+'\> '+culang.OlddfUpdateIntervall+' <INPUT id=pbmsgint type=text size=3 maxlength=3 value='+AttackOptions.UpdateInterval+' \> '+culang.mainMinutes+'</td></tr>';
		y +='<TR><TD>'+culang.OlddfSkip+' <INPUT id=barbstopsearch type=text size=4 value='+AttackOptions.stopsearch+' \> '+culang.OlddfSkip2+'</td></tr>';
		y +='<TR><TD>'+culang.OlddfMethode+': '+htmlSelector({distance:''+culang.mainDistance+'', level:''+culang.OlddfSelectMethodeHighLevel+'', lowlevel:''+culang.OlddfSelectMethodeLowLevel+''}, AttackOptions.Method, 'id=pbmethod')+'</td></tr>';
		var yy = htmlSelector({0:culang.OlddfSelectKnightLowCom, 1:culang.OlddfSelectKnightHighCom, 2:culang.OlddfSelectKnightLowPol, 3:culang.OlddfSelectKnightHighPol, 4:culang.OlddfSelectKnightLowInt, 5:culang.OlddfSelectKnightHighInt, 6:culang.OlddfSelectKnightLowRes, 7:culang.OlddfSelectKnightHighRes, 8:culang.OlddfSelectKnightLowSum, 9:culang.OlddfSelectKnightHighSum}, AttackOptions.knightselector, 'id=barbknight');
		y +='<TR><TD>'+culang.OlddfKnightSelector+': '+yy+'</td></tr>';
		y+='<tr><td>'+culang.OlddfResetValues+': <input type=button value="'+culang.mainReset+'" id=Ks_FO_razCompteur></table></td></tr></table>';
		t.barboptions.getMainDiv().innerHTML = y;
		t.barboptions.show(true);

		ById('Ks_FO_razCompteur').addEventListener('click', function(){
			AttackOptions.BarbsFailedTraffic=0;
			AttackOptions.BarbsFailedKnight=0;
			AttackOptions.BarbsFailedVaria=0;
			AttackOptions.BarbsFailedMarais=0;
			AttackOptions.BarbsFailedRP=0;
			AttackOptions.BarbsFailedBog=0;
			AttackOptions.BarbsTried=0;
			for (var city=0;city<Seed.cities.length;city++)
				AttackOptions.BarbsDone[city]=0;

			saveAttackOptions();
		},false);
		ById('pbcity').options.length=0;
		for (i=0;i<Seed.cities.length;i++){
			var o = document.createElement("option");
			o.text = Seed.cities[i][1]
			o.value = i+1;
			ById("pbcity").options.add(o);
		}

		ById('pbpaintbarbs').addEventListener('click', function(){
			t.showBarbs(ById("pbcity").value,Seed.cities[ById("pbcity").value -1][1]);
		},false);
		ById('pbresetbarbs').addEventListener('click', t.deletebarbs,false);
		ById('pbmethod').addEventListener('change', function(){
			AttackOptions.Method=ById('pbmethod').value;
			saveAttackOptions();
			t.checkBarbData();
		},false);
		ById('barbknight').addEventListener('change', function(){
			AttackOptions.knightselector=ById('barbknight').value;
			saveAttackOptions();
		},false);
		ById('pbreport').addEventListener('change', function(){
			AttackOptions.UpdateEnabled=ById('pbreport').checked;
			saveAttackOptions();
		},false);
		ById('pbmsgint').addEventListener('change', function(){
			if (parseInt(ById('pbmsgint').value)<15) ById('pbmsgint').value=15;
			AttackOptions.UpdateInterval=parseInt(ById('pbmsgint').value);
			saveAttackOptions();
		},false);
		ById('pbsendint').addEventListener('change', function(){
			if(parseInt(ById('pbsendint').value) <5) //Set minimum attack interval to 5 seconds
				ById('pbsendint').value = 5;
			AttackOptions.SendInterval=parseInt(ById('pbsendint').value);
			saveAttackOptions();
		},false);
		ById('pbmaxdist').addEventListener('change', function(){
			if(parseInt(ById('pbmaxdist').value) > 75)
				ById('pbmaxdist').value = 75;
			AttackOptions.MaxDistance=parseInt(ById('pbmaxdist').value);
			saveAttackOptions();
		},false);
		ById('rallyclip').addEventListener('change', function(){
			AttackOptions.RallyClip=parseInt(ById('rallyclip').value);
			saveAttackOptions();
		},false);
		ById('barbstopsearch').addEventListener('change', function(){
			ById('barbstopsearch').value = parseInt(ById('barbstopsearch').value)>0?ById('barbstopsearch').value:1
			AttackOptions.stopsearch=parseInt(ById('barbstopsearch').value);
			saveAttackOptions();
		},false);
	},

	showBarbs: function (citynumber,cityname) {
		var t = Tabs.MercenaryCamps;
		var popTradeRoutes = null;
		t.popTradeRoutes = new CPopup('pbShowBarbs', 0, 0, 500, 500, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';
		t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
		t.popTradeRoutes.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.OlddfListPopupHead+' '+cityname+'</div>';
		t.popTradeRoutes.centerMe (mainPop.getMainDiv());
		t.paintBarbs(citynumber,cityname);
		t._addTabHeader(citynumber,cityname);
		t.popTradeRoutes.show(true)	;
	},
	paintBarbs: function(i,cityname){
		var t = Tabs.MercenaryCamps;
		for (k=(t.barbArray[i].length-1);k>=0;k--){t._addTab(i,cityname,k+1,t.barbArray[i][k]['x'], t.barbArray[i][k]['y'],t.barbArray[i][k]['dist'], t.barbArray[i][k]['level']);}
	},

	_addTab: function(citynumber,cityname,queueId,X,Y,dist,level){
		var t = Tabs.MercenaryCamps;
		var row = ById('pbBars').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = queueId;
		row.insertCell(1).innerHTML = '<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+X+','+Y+')</a>';
		row.insertCell(2).innerHTML = '';
		row.insertCell(3).innerHTML = dist;
		row.insertCell(4).innerHTML = level;
		row.insertCell(5).innerHTML = '<a id="barbdel_' + queueId + '"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a>';
		ById('barbdel_' + queueId).addEventListener('click', function(){
			t.deleteBarbElement(citynumber,queueId,cityname, true);
		}, false);
	},

	_addTabHeader: function(citynumber,cityname) {
		var t = Tabs.MercenaryCamps;
		var row = ById('pbBars').insertRow(0);
		row.vAlign = 'top';
		row.insertCell(0).innerHTML = culang.mainCastle;
		row.insertCell(1).innerHTML = culang.shortCoordinate;
		row.insertCell(2).innerHTML = "";
		row.insertCell(3).innerHTML = culang.shortDistance;
		row.insertCell(4).innerHTML = uW.g_js_strings.commonstr.level;
		row.insertCell(5).innerHTML = '<a id="barbdelAll"><span><img src="'+IMGdeleteButton+'" title="'+culang.mainDeleteAll+'"></span></a>';
		ById('barbdelAll').addEventListener('click', function(){
			t.deleteBarbsCity(citynumber,cityname);
		}, false);
	},

	deleteBarbElement: function(citynumber,queueId,cityname,showFlag){
		var t = Tabs.MercenaryCamps;
		var queueId = parseInt(queueId);
		var myarray = t.barbArray[citynumber];
		if (myarray) {
			myarray.splice((queueId-1), 1);
			GM_setValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(myarray));
			t.checkBarbData();
			if (showFlag) t.showBarbs(citynumber,cityname);
		}
	},
	deleteBarbsCity: function(citynumber,cityname){
		var t = Tabs.MercenaryCamps;
		var queueId = parseInt(queueId);
		AttackOptions.Update[citynumber][1] = 0;
		GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId())
		t.checkBarbData();
		t.showBarbs(citynumber,cityname);
		actionLog(""+culang.OldmainDarkForest+"",""+culang.refreshDFActionLog+"");
		reloadKOC();
	},
	saveTroops: function(){
		for(i=0;i<10;i++){
			for (w=0;w<16;w++){
				if (ById('level'+i+'troop'+w).value.toUpperCase() == "MAX") {
					AttackOptions.Troops[i+1][w+1] = "MAX";
				} else {
					AttackOptions.Troops[i+1][w+1] = parseIntNan(ById('level'+i+'troop'+w).value);
				}
			}
		}
		saveAttackOptions();
	},

	deletebarbs: function(){
		var t = Tabs.MercenaryCamps;
		for (i=1;i<=Seed.cities.length;i++){
			AttackOptions.Update[i][1] = 0;
			GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
			t.barbArray[i] = []; 
			GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[i]));
		}
		saveAttackOptions();
		//actionLog(""+culang.OldmainDarkForest+"",""+culang.OldrefreshDFActionLog+"");
		//reloadKOC();
	},

	checkBarbData: function(){
		var t = Tabs.MercenaryCamps;
		if(!Options.AttackRunning) return;
		for (i=1;i<=Seed.cities.length;i++){
			if (!AttackOptions.Levels[i][0]) continue; //Skip city if not selected
			t.barbArray[i] = [];
			var myarray = JSON2.parse(GM_getValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(),"[]"));

			if ((myarray == undefined || myarray.length == 0) && t.searchRunning==false) {
				t.lookup=i;
				if(parseInt(AttackOptions.Update[t.lookup][1]) >= parseInt(AttackOptions.stopsearch)) continue; //Skip if search results are empty more than X times
				t.searchRunning = true;
				t.opt.startX = parseInt(Seed.cities[(i-1)][2]);
				t.opt.startY = parseInt(Seed.cities[(i-1)][3]);
				t.clickedSearch();
				break;
			}
			if (myarray){
				if(AttackOptions.Method == 'distance') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
				if(AttackOptions.Method == 'level') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = parseInt(a['level']);b = parseInt(b['level']);return a == b ? 0 : (a > b ? -1 : 1);});
				if(AttackOptions.Method == 'lowlevel') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = parseInt(a['level']);b = parseInt(b['level']);return a == b ? 0 : (a < b ? -1 : 1);});
				GM_setValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.barbArray[i]));
			}
			AttackOptions.Update[i][1] = 0;
			saveAttackOptions();
		}
		t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*3000)+2000));
	},

	toggleBarbState: function(obj){
		var t = Tabs.MercenaryCamps;
		obj = ById('AttSearch2');
		if (parseInt(AttackOptions.UpdateInterval)<15) AttackOptions.UpdateInterval=15;
		if (Options.AttackRunning == true) {
			Options.AttackRunning = false;
			obj.value = culang.OldmainDarkForest+" = "+culang.OldbuttonOFF;
			saveAttackOptions();saveOptions();
			clearTimeout(t.nextattack);
			t.nextattack = null;
		} else {
			Options.AttackRunning = true;
			obj.value = culang.OldmainDarkForest+" = "+culang.OldbuttonON;
			saveAttackOptions();saveOptions();
			t.checkBarbData();
			t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*3000)+2000));
		}
	},

	barbing : function(){
		var t = Tabs.MercenaryCamps;
		var city = t.city;
		citynumber = Seed.cities[city-1][0];
		cityID = 'city' + citynumber;
		t.getAtkKnight(citynumber);
		var rinfo = getRallypointInfo(citynumber);
		t.rallypointlevel = rinfo.maxMarches;
		var slots = rinfo.usedSlots;
		var maxtroupe = rinfo.maxMarchSize;
		
		var element1 = 'pddatacity'+(city-1);
		ById(element1).innerHTML = ''+culang.OlddfBarbsDone+' ' + AttackOptions.BarbsDone[city];
		var element2 = 'pddataarray'+(city-1);
		ById(element2).innerHTML =  ''+culang.mainSRallyPoint+': (' + slots + '/' + t.rallypointlevel +')';

		if ((t.rallypointlevel-AttackOptions.RallyClip) <= slots) {
			actionLog(""+culang.OldmainDarkForest+"",""+culang.OlddfNoFreeSlots+"");
			return;
		}
		if (t.knt.toSource() == "[]") {
			actionLog(""+culang.OldmainDarkForest+"",""+culang.OlddfNoKnights+"");
			return;
		}
		var kid = t.knt[0].ID;

		if(t.barbArray[city].length > 0)
			var barbinfo = t.barbArray[city].shift();
		else if(!t.searchRunning){
			t.checkBarbData();
			return;
		} else {
			return;
		}
		var check=0;
		var barblevel = parseInt(barbinfo.level);
		if (AttackOptions.Levels[city][barbinfo.level])
			check=1;


		var xcoord = barbinfo['x'];
		var ycoord = barbinfo['y'];
		if (barbinfo.dist > AttackOptions.MaxDistance){
			check=0;
			GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
			return;
		}

		// check troop levels in city
		var trps = AttackOptions.Troops[barblevel];

		var troops = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    for (y=1;y<17;y++){
    	if (trps[y] == "MAX") {
    		var total=0;
    		for (var yy=1;yy<17;yy++) if (y!=yy) total+=parseInt(trps[yy]);
    		troops[y] =  maxtroupe - total;
    	}
    	else troops[y] = trps[y];
    }
		
		
		var num_troops = 0;		
		for (var ii=1; ii<17; ii++) {
			if (parseIntNan(troops[ii]) > Seed.units[cityID]['unt'+ii]) check = 0;
			num_troops += trps[ii];
		}
		if (num_troops == 0) check = 0;
		
		if (check == 0){
			t.barbArray[city].push(barbinfo);
			GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
			actionLog(""+culang.OldmainDarkForest+"",""+culang.OlddfLogNoTroops+" "+parseInt(barblevel)+" "+culang.OlddfLogNoTroops2+"");
			return;
		}

		var element = 'pdtotalcity'+(city-1);
		if (t.barbArray[city] == undefined) ById(element).innerHTML = '<i>'+culang.OlddfNoData+'</i>';
		else ById(element).innerHTML =  ''+culang.OlddfShort+' ' + t.barbArray[city].length;

		var xcoord = barbinfo['x'];
		var ycoord = barbinfo['y'];


		t.doBarb(citynumber,city,xcoord,ycoord,barblevel,kid,troops);
		saveAttackOptions();
	},

	getnextCity: function(){
		var t = Tabs.MercenaryCamps;
		clearTimeout(t.nextattack);
		if(t.searchRunning || !Options.AttackRunning) return;
		var en = false;
		for (var i=1;i<=Seed.cities.length;i++) {
			if (AttackOptions.Levels[i][0]) en = true;
		}
		if (en) t.nextattack = setTimeout(t.getnextCity, AttackOptions.SendInterval*1000);
		do {
			var city = t.city+1;
			if (city>Seed.cities.length){
				city=1;
			}
			t.city = city;
			en = false;
			for (var i=1;i<=Seed.cities.length;i++) {
				if (AttackOptions.Levels[i][0]) en = true;
			}
		} while (!AttackOptions.Levels[city][0] && en);
		
		if(AttackOptions.UpdateEnabled){
			var now = unixTime();
			if(now > parseInt(AttackOptions.Update[city][0] + (AttackOptions.UpdateInterval*60))){
				AttackOptions.Update[city][1]=0;
				t.barbArray[city] = []; //Clears data if last update was more than X minutes
				GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
			}
		}

		if(AttackOptions.Levels[city][0])
			t.barbing();
	},

	getAtkKnight : function(cityID){
		var t = Tabs.MercenaryCamps;
		t.knt = new Array();
		var rinfo = getRallypointInfo(cityID);
		t.rallypointlevel = rinfo.maxMarches;
		for (k in Seed.knights['city'+cityID]){
			if (Seed.knights['city'+cityID][k]["knightStatus"] == 1 && 
					Seed.leaders['city'+cityID]["resourcefulnessKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
					Seed.leaders['city'+cityID]["politicsKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
					Seed.leaders['city'+cityID]["combatKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
					Seed.leaders['city'+cityID]["intelligenceKnightId"] != Seed.knights['city'+cityID][k]["knightId"]){
				t.knt.push ({
					Name:   Seed.knights['city'+cityID][k]["knightName"],
					ID:		Seed.knights['city'+cityID][k]["knightId"],					
					Combat:	parseIntNan(Seed.knights['city'+cityID][k]["combat"]),
					Politics:	parseIntNan(Seed.knights['city'+cityID][k]["politics"]),
					Intelligence:	parseIntNan(Seed.knights['city'+cityID][k]["intelligence"]),
					Resourcefulness:	parseIntNan(Seed.knights['city'+cityID][k]["resourcefulness"]),
					Experience: parseIntNan(Seed.knights['city'+cityID][k]["experience"]),
				});
			}
		}
		t.knt = t.knt.sort(function sort(a,b) {
			var ac = a['Combat'];
			var bc = b['Combat'];
			var ap = a['Politics'];
			var bp = b['Politics'];
			var ai = a['Intelligence'];
			var bi = b['Intelligence'];
			var ar = a['Resourcefulness'];
			var br = b['Resourcefulness'];
			var as = a['Experience'];
			var bs = b['Experience'];
			var type = parseIntNan(AttackOptions.knightselector);
			switch(type) {
				case 0:
					var erg = ac == bc ? 0 : (ac < bc ? -1 : 1);
					break;
				case 1:
					var erg = ac == bc ? 0 : (ac > bc ? -1 : 1);
					break;
				case 2:
					var erg = ap == bp ? 0 : (ap < bp ? -1 : 1);
					break;
				case 3:
					var erg = ap == bp ? 0 : (ap > bp ? -1 : 1);
					break;
				case 4:
					var erg = ai == bi ? 0 : (ai < bi ? -1 : 1);
					break;
				case 5:
					var erg = ai == bi ? 0 : (ai > bi ? -1 : 1);
					break;
				case 6:
					var erg = ar == br ? 0 : (ar < br ? -1 : 1);
					break;
				case 7:
					var erg = ar == br ? 0 : (ar > br ? -1 : 1);
					break;	
				case 8:
					var erg = as == bs ? 0 : (as < bs ? -1 : 1);
					break;
				case 9:
					var erg = as == bs ? 0 : (as > bs ? -1 : 1);
					break;
			}
			return erg;
		});
	},
	doBarb: function(cityID,counter,xcoord,ycoord,level,kid,trps){
		var t = Tabs.MercenaryCamps;
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.cid=cityID;
		params.type=4;
		params.kid=kid;
		params.xcoord = xcoord;
		params.ycoord = ycoord;
		for (ii=1; ii<17; ii++) {
			if(parseIntNan(trps[ii]) > 0)
				params['u'+ii]=parseIntNan(trps[ii]);
		}

		AttackOptions.BarbsTried++;
		ById('pberror0').innerHTML = ''+culang.OlddfTries+': '+ AttackOptions.BarbsTried;
		new AjaxRequest(uW.g_ajaxpath + "ajax/march.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			loading: true,
			onSuccess: function (transport) {
			  try {
				var rslt = eval("(" + transport.responseText + ")");
				if (rslt.ok) {
					var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
          var rtimediff = parseInt(rslt.returnTS) - parseInt(rslt.initTS);
					var ut = uW.unixtime();
					var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
							unitsarr[i] = params["u"+i];
						}
					}
					var resources=new Array();
					resources[0] = params.gold;
					for(i=1; i<=4; i++){
						resources[i] = params["r"+i];
					}
					var currentcityid = params.cid;
					uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true, ut + rtimediff);
               
					if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
					var slots=0;
					for(var k in Seed.queue_atkp['city'+cityID])
						slots++;
					if(Seed.queue_atkp['city'+cityID].toSource() == "[]")
						slots = 0;
					AttackOptions.BarbsDone[counter]++;
					var element1 = 'pddatacity'+(counter-1);
					ById(element1).innerHTML = ''+culang.OlddfBarbsDone+' ' + AttackOptions.BarbsDone[counter];
					var element2 = 'pddataarray'+(counter-1);
					ById(element2).innerHTML =  ''+culang.mainSRallyPoint+': (' + slots + '/' + t.rallypointlevel +')';
					var now = new Date().getTime()/1000.0;
					now = now.toFixed(0);
					GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
					saveAttackOptions();
				} else {
					if (rslt.error_code != 8 && rslt.error_code != 213 && rslt.error_code == 210) AttackOptions.BarbsFailedVaria++;
					if (rslt.error_code == 213)AttackOptions.BarbsFailedKnight++;
					if (rslt.error_code == 210) AttackOptions.BarbsFailedRP++;
					if (rslt.error_code == 8) AttackOptions.BarbsFailedTraffic++;
					if (rslt.user_action) {
						actionLog(""+culang.OldmainDarkForest+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
						new CdialogCancelContinue('<SPAN class=boldRed>'+culang.darkForestCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);
						AttackOptions.BarbsFailedVaria++;
					}
					if (rslt.error_code == 104) {
						AttackOptions.BarbsFailedBog++;
						GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
						saveAttackOptions();
					}
					ById('pberror2').innerHTML = '<div title="'+culang.OlddfReportConnectionError+'">'+culang.OlddfReportShortConnectionError+':</div> ' + AttackOptions.BarbsFailedTraffic;
					ById('pberror3').innerHTML = '<div title="'+culang.OlddfReportRPError+'">'+culang.OlddfReportShortRPError+':</div> '+ AttackOptions.BarbsFailedRP;
					ById('pberror4').innerHTML = ''+culang.OlddfReportKnightsError+': ' + AttackOptions.BarbsFailedKnight;
					ById('pberror5').innerHTML = ''+culang.OlddfReportMoreError+': ' + AttackOptions.BarbsFailedVaria;
					ById('pberror6').innerHTML = ''+culang.OlddfReportBogError+': ' + AttackOptions.BarbsFailedBog;
				}
				 } catch(err) {
			   	AttackOptions.BarbsFailedVaria++;
			   	saveAttackOptions();
			   }
			},
			onFailure: function () {}
		});
		saveAttackOptions();
	},

	clickedSearch : function (){
		var t = Tabs.MercenaryCamps;

		t.opt.maxDistance = parseInt(AttackOptions.MaxDistance);
		t.opt.searchDistance = 20;
		t.opt.searchShape = 'circle';
		t.mapDat = [];
		t.koordlist = [];
		t.firstX =  t.opt.startX - t.opt.maxDistance;
		t.lastX = t.opt.startX + t.opt.maxDistance;
		t.firstY =  t.opt.startY - t.opt.maxDistance;
		t.lastY = t.opt.startY + t.opt.maxDistance;
		t.tilesSearched = 0;
		t.tilesFound = 0;
		t.curX = t.firstX;
		t.curY = t.firstY;
		var xxx = t.MapAjax.normalize(t.curX);
		var yyy = t.MapAjax.normalize(t.curY);
		var element = 'pddatacity'+(t.lookup-1);
		ById(element).innerHTML = culang.searchSearched+' '+ xxx +','+ yyy;
		t.timerMap=setTimeout (function(){t.MapAjax.request (xxx, yyy, 20, t.mapCallback)}, 1000);
	},
	timerMap:null,
	mapCallback : function (left, top, width, rslt){
		var t = Tabs.MercenaryCamps;
		if (!t.searchRunning)
			return;
		if (!rslt.ok){
			t.stopSearch (''+culang.mainError+': '+ rslt.errorMsg);
			return;
		}
		if (!Options.AttackRunning) {
			for (i=1;i<=Seed.cities.length;i++){
				AttackOptions.Update[i][1] = 0;
				GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
			}
			var element = 'pddatacity'+(t.lookup-1);
			ById(element).innerHTML = ''+culang.OlddfCancelByUser+'';
			t.searchRunning = false;
			saveAttackOptions();
			return;
		}
		
		if (rslt.error_code == 9) {
			var element = 'pddatacity'+(t.lookup-1);
			document.getElementById(element).innerHTML = 'MAP-Error (60sec): '+ left +','+ top;
			setTimeout (function(){
				var element = 'pddatacity'+(t.lookup-1);
				document.getElementById(element).innerHTML = ''+culang.searchSearched+' '+ left +','+ top;
				t.MapAjax.request (left, top, 20, t.mapCallback);
			}, 61000);
			return;
		}
		map = rslt.data;

		for (k in map){
			if (map[k].tileType==54 || map[k].tileType==0) {
				var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
				if(dist <= parseInt(AttackOptions.MaxDistance)) {
					//Puffer fuer relevante Koords
					//t.koordlist.push({x:map[k].xCoord,y:map[k].yCoord});
					if (map[k].tileType==54 && AttackOptions.Levels[t.lookup][map[k].tileLevel]){
						t.mapDat.push ({time:0,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel});
					}
				}
			}
		}

		t.tilesSearched += (t.opt.searchDistance*t.opt.searchDistance);

		t.curX += t.opt.searchDistance;
		if (t.curX > t.lastX){
			t.curX = t.firstX;
			t.curY += t.opt.searchDistance;
			if (t.curY > t.lastY){
				t.stopSearch(''+culang.OlddfFound+' ' + t.mapDat.length);
				//alert(t.koordlist.length);
				return;
			}
		}
		var x = t.MapAjax.normalize(t.curX);
		var y = t.MapAjax.normalize(t.curY);
		var element = 'pddatacity'+(t.lookup-1);
		ById(element).innerHTML = ' '+culang.searchSearched+' '+ x +','+ y;
		t.timerMap=setTimeout (function(){t.MapAjax.request (x, y, t.opt.searchDistance, t.mapCallback)}, MAP_DELAY);
	},


	stopSearch : function (msg){
		var t = Tabs.MercenaryCamps;
		var element = 'pddatacity'+(t.lookup-1);
		ById(element).innerHTML = msg;
		GM_setValue('DF_' + Seed.player['name'] + '_city_' + t.lookup + '_' + getServerId(), JSON2.stringify(t.mapDat));
		AttackOptions.Update[t.lookup][0] = unixTime();
		AttackOptions.Update[t.lookup][1]++;
		t.searchRunning = false;
		saveAttackOptions();
		t.checkBarbData();
		return;
	},

	hide : function (){

	},

	show : function (){

	},

};


//</editor-fold>
function saveAttackOptions (){
	var serverID = getServerId();
	setTimeout (function (){GM_setValue ('AttackOptions_'+serverID, JSON2.stringify(AttackOptions));}, 0);
}

function readAttackOptions (){
	var serverID = getServerId();
	s = GM_getValue ('AttackOptions_'+serverID);
	if (s != null){
		opts = JSON2.parse (s);
		for (k in opts){
			if (matTypeof(opts[k]) == 'object')
				for (kk in opts[k])
					AttackOptions[k][kk] = opts[k][kk];
			else
				AttackOptions[k] = opts[k];
		}
	}
}
/*********************************** News TAB ***********************************/
Tabs.News = {
    tabOrder: 301,
  tabDisabled : false,
  tabLabel : 'Ally msg',
  myDiv : null,
  
    init : function (div){
        var t = Tabs.News;
        t.myDiv = div;
    div.innerHTML = '<DIV class=pbStat>Important Info!</div><br>';
        GM_xmlhttpRequest({
            method: 'GET',
            url: 'http://mad-hatters-magic-elite.googlecode.com/svn/trunk/BreakingNews.txt',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            onload: function (news) {
                if(news.status != 200) {
                     div.innerHTML += '<center><div  style="background-color:#DEDEDE; width:600px; height:200px;  text-align:left; overflow-y:auto;"><b>Unable to fetch news  <br>Error: '+news.status+'</b></div></center>';
                    return;
                }
                var m = '<center>';
                 m += '<div style="background-color:#DEDEDE; width:600px;  height:200px; text-align:left; overflow-y:auto;">';
                m += '<div id=newsdate></div>'
                m += '<b>'+news.responseText.replace(/\n/g,"<br>")+'</b>';
                m += '</div></center>';
                 m += '<div><font color =  red>&nbsp&nbsp&nbsp&nbspIntended to only be used for  updates and moral.  <br>&nbsp&nbsp&nbsp&nbspex:  kabam Fixed view misted city through bookmark glitch</div>';
                div.innerHTML += m;
                var first = Number(news.responseHeaders.indexOf("Last-Modified"))+15;
                var last = news.responseHeaders.indexOf("\n",first);
                var lastmodified = news.responseHeaders.slice(first,last);
                if (Options.BreakingNews != lastmodified) {
                    Options.BreakingNews=lastmodified;
                    Options.BreakingNewsV = true;
                    saveOptions();
                }
                if(Options.BreakingNewsV == true)
                setTimeout(t.notify,10000);
                 document.getElementById('newsdate').innerHTML = '<p  style="text-align: right;">'+Options.BreakingNews+'</p>';
            },
        });
    },
  hide : function (){
    var t = Tabs.News;
  },

  show : function (){
    var t = Tabs.News;
    Options.BreakingNewsV = true;
    saveOptions();
  },
  notify : function() {
    var t = Tabs.News;
    var elem = document.getElementById("pbtcNews");
elem.setAttribute("style","background: -moz-linear-gradient(center top , #ff0000, #b10000) repeat scroll 0 0 transparent;");
  },

}
Tabs.Scripter = {
    tabOrder: 99000,
    tabDisabled : !Options.ScripterTab,
    tabLabel : 'Scripter',
    myDiv : null,
    
    init : function (div) {
        var t = Tabs.Scripter
        t.myDiv = div;
        var m = '<DIV class=pbStat>Scripter</div><br>';
        m += '<center><INPUT id=SCode type=text size=70 maxlength=9999 value="" \></center>'
        div.innerHTML = m;
        
        document.getElementById('SCode').addEventListener ('keypress', function (e){
        if(e.which == 13)
            eval(this.value);
        }, false);
    },
  hide : function (){
    var t = Tabs.Scripter;
  },

  show : function (){
    var t = Tabs.Scripter;
  },  
}

/*********************************** Q&A TAB ***********************************/
Tabs.QA = {
    tabOrder: 302,
  tabDisabled : true,
  tabLabel : 'Q&A',
  myDiv : null,
  
    init : function (div){
        var t = Tabs.QA;
        t.myDiv = div;
    div.innerHTML = '<DIV class=pbStat>Questions And Answers</div><br>';
        GM_xmlhttpRequest({
            method: 'GET',
            url: 'http://alliance-q-and-a-board.googlecode.com/svn/trunk/Q&A.txt',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            onload: function (news) {
                if(news.status != 200) {
                     div.innerHTML += '<center><div  style="background-color:#DEDEDE; width:600px; height:200px;  text-align:left; overflow-y:auto;"><b>Unable to fetch news  <br>Error: '+news.status+'</b></div></center>';
                    return;
                }
                var m = '<center>';
                 m += '<div style="background-color:#DEDEDE; width:600px;  height:200px; text-align:left; overflow-y:auto;">';
                m += '<div id=newsdate></div>'
                m += '<b>'+news.responseText.replace(/\n/g,"<br>")+'</b>';
                m += '</div></center>';
                 m += '<div><font color =  red>&nbsp&nbsp&nbsp&nbspIntended for q&a  support.  <br>&nbsp&nbsp&nbsp&nbspex: Question  what is the best troop to defend with if being hit by cats and range?   Answer Defend with ponies and either CS or defense.</div>';
                div.innerHTML += m;
                var first = Number(news.responseHeaders.indexOf("Last-Modified"))+15;
                var last = news.responseHeaders.indexOf("\n",first);
                var lastmodified = news.responseHeaders.slice(first,last);
                if (Options.BreakingNews != lastmodified) {
                    Options.BreakingNews=lastmodified;
                    Options.BreakingNewsV = false;
                    saveOptions();
                }
                if(Options.BreakingNewsV == false)
                setTimeout(t.notify,10000);
                 document.getElementById('newsdate').innerHTML = '<p  style="text-align: right;">'+Options.BreakingNews+'</p>';
            },
        });
    },
  hide : function (){
    var t = Tabs.QA;
  },

  show : function (){
    var t = Tabs.QA;
    Options.BreakingNewsV = true;
    saveOptions();
  },
  notify : function() {
    var t = Tabs.QA;
    var elem = document.getElementById("pbtcNews");
elem.setAttribute("style","background: -moz-linear-gradient(center top , #ff0000, #b10000) repeat scroll 0 0 transparent;");
  },

}
Tabs.Scripter = {
    tabOrder: 99000,
    tabDisabled : !Options.ScripterTab,
    tabLabel : 'Scripter',
    myDiv : null,
    
    init : function (div) {
        var t = Tabs.Scripter
        t.myDiv = div;
        var m = '<DIV class=pbStat>Scripter</div><br>';
        m += '<center><INPUT id=SCode type=text size=70 maxlength=9999 value="" \></center>'
        div.innerHTML = m;
        
        document.getElementById('SCode').addEventListener ('keypress', function (e){
        if(e.which == 13)
            eval(this.value);
        }, false);
    },
  hide : function (){
    var t = Tabs.Scripter;
  },

  show : function (){
    var t = Tabs.Scripter;
  },  
}
/**************************** Start Up Tab ******************************************/

var buildingIDs = {
    Farm:1,Mine:4,Quarry:3,Sawmill:2,Castle:0,Wall:19,Barracks:13,Cottage:5,RelStat:18,Stable:17,Blacksmith:15,KnightsHall:7,Workshop:16,FeySpire:20,Apothecary:21,RallyPoint:12,Embassy:8,AlcLab:11,Nothing:0,WatchTower:14
    };
var buildingTypes = {
    type5:"Cottage",type6:"",type7:"KnightsHall",type8:"Embassy",type9:"",type10:"",type11:"AlcLab",type12:"RallyPoint",type13:"Barracks",type14:"WatchTower",type15:"Blacksmith",type16:"Workshop",type17:"Stable",type18:"RelStation",type19:"Wall",type20:"FeySpire",type21:"Apothecary",
};
var cityBuildingNames = {
    Wall:"Wall",Cottage:"Cottage",Barracks:"Barracks",Blacksmith:"Blacksmith",Stable:"Stable",Apothecary:"Apothecary",Workshop:"Workshop",FeySpire:"Fey Spire",Embassy:"Embassy",RelStation:"Relief Station",AlcLab:"Alchemy Lab",WatchTower:"Watch Tower",KnightsHall:"Knights Hall",RallyPoint:"Rally Point",
    };
var fieldBuildingNames = {
    Farm:"Farm",Mine:"Mine",Sawmill:"Mill",Quarry:"Quarry",
    };
var layoutOptions = {
    pos1:"Wall",pos2:"Barracks",pos3:"Cottage",pos4:"RelStation",pos5:"Barracks",pos6:"Barracks",pos7:"Barracks",pos8:"Stable",pos9:"KnightsHall",pos10:"RallyPoint",pos11:"Barracks",pos12:"Barracks",pos13:"Barracks",pos14:"Cottage",pos15:"FeySpire",pos16:"Apothecary",pos17:"Blacksmith",pos18:"Workshop",pos19:"AlcLab",pos20:"Barracks",pos21:"Barracks",pos22:"Barracks",pos23:"Embassy",pos24:"Cottage",pos25:"Barracks",pos26:"Barracks",pos27:"Barracks",pos28:"Cottage",pos29:"Cottage",pos30:"Barracks",pos31:"Barracks",pos32:"Cottage"
    };
var fieldlayoutOptions = {
    pos100:"Farm",pos101:"Sawmill",pos104:"Quarry",pos105:"Mine",pos102:"Mine",pos103:"Mine",pos106:"Mine",pos107:"Mine",pos108:"Mine",pos109:"Mine",pos110:"Mine",pos111:"Mine",pos112:"Mine",pos113:"Mine",pos114:"Mine",pos115:"Mine",pos116:"Mine",pos117:"Mine",pos118:"Mine",pos119:"Mine",pos120:"Mine",pos121:"Mine",pos122:"Mine",pos123:"Mine",pos124:"Mine",pos125:"Mine",pos126:"Mine",pos127:"Mine",pos128:"Mine",pos129:"Mine",pos130:"Mine",pos131:"Mine",pos132:"Mine",pos133:"Mine",pos134:"Mine",pos135:"Mine",pos136:"Mine",pos137:"Mine",pos138:"Mine",pos139:"Mine",pos142:"Mine"
    };  
var AscbuildingIDs = {
    Castle:0,Wall:19,Barracks:13,Cottage:5,KnightsHall:7,FeySpire:20,RallyPoint:12,Embassy:8,AlcLab:11,Nothing:0,Wall:19,Market:10,Apothecary:21,WatchTower:14
    };
var AscbuildingTypes = {
    type5:"Cottage",type6:"",type7:"KnightsHall",type8:"Embassy",type9:"",type10:"Market",type11:"AlcLab",type12:"RallyPoint",type13:"Barracks",type14:"WatchTower",type19:"Wall",type20:"FeySpire",type21:"Apothecary"
};
var AsccityBuildingNames = {
    Wall:"Wall",Cottage:"Cottage",Barracks:"Barracks",Apothecary:"Apothecary",FeySpire:"Fey Spire",Embassy:"Embassy",AlcLab:"Alchemy Lab",WatchTower:"Watch Tower",KnightsHall:"Knights Hall",RallyPoint:"Rally Point",Market:"Market"
    };

Tabs.startup = {
    tabOrder : 99999,
    tabDisabled : false,
    tabLabel : 'StartUp',
    myDiv : null,
    where: 'City', //Initialize to city by default


    init : function (div){
        var t = Tabs.startup;
        t.myDiv= div;
        var counter=0;
        var m = '<DIV id=pbStartupDiv class=pbStat>New Domain Tools</div><TABLE id=pbNewDomain width=100% height=0% class=pbTab><TR align="center">';
        m += '<DIV id=pblvlcity align=center></div><DIv><INPUT id=addToBuildQueue type=submit value="Add to build queue"></div>';
        m += '<INPUT id=toggleFieldLayout type=submit value="Show Field Layout"><INPUT id=toggleCityLayout type=submit value="Show City Layout"><INPUT id=hideGrids type=submit value="Hide Layouts">';
        m += '<DIV id=mainTitles></div>';    
        m += '<DIV id=gridPicture></div>';
           m += '<DIV id=layoutBoxes></div>';
          
        t.myDiv.innerHTML = m;
        t.city = new CdispCityPicker ('pblvlcity', document.getElementById('pblvlcity'), true, t.ClickCitySelect, 0);

        document.getElementById('toggleFieldLayout').addEventListener('click', function () {
                t.paintFieldGrid();
        });
        document.getElementById('toggleCityLayout').addEventListener('click', function () {
                t.paintCityGrid();
        });
        document.getElementById('hideGrids').addEventListener('click', function () {
                document.getElementById('mainTitles').innerHTML = "";
                document.getElementById('gridPicture').innerHTML = "";
                document.getElementById('layoutBoxes').innerHTML = "";

        });
        document.getElementById('addToBuildQueue').addEventListener('click', function () {
            if (t.where == "City") t.addCityToQueue();
            if (t.where == "Field") t.addFieldToQueue();
        });
    },
    ClickCitySelect : function(){ //Call this function when users switch to another city
        var t = Tabs.startup;
        switch(t.where){
            case 'City':
                t.paintCityGrid();
                break;
            case 'Field':
                t.paintFieldGrid();
                break;
            default : //If somehow something goes wrong then paint city view by default
                t.paintCityGrid();
                break;
        }
    },
    getCastleLevel:function(){
        var t = Tabs.startup
    var castle = Seed.buildings["city" + t.city.city.id]["pos0"][1];
        switch(castle){
                case "1":fields = 13;break;
                case "2":fields = 16;break;
                case "3":fields = 19;break;
                case "4":fields = 22;break;
                case "5":fields = 25;break;
                case "6":fields = 28;break;
                case "7":fields = 31;break;
                case "8":fields = 34;break;
                case "9":fields = 37;break;
                case "10":fields = 40;break;
                case "11":fields = 41;break;
                case "12":fields = 42;break;
        }
        max = (fields-1) + 100;
        return(max)
    },

    addCityToQueue:function(){
        var t = Tabs.startup;
   var AscCityInd = Seed.cityData.city[t.city.city.id].isPrestigeCity;
            for (pos=1;pos<=32;pos++){
      if(AscCityInd == true) {
                      if  (AscbuildingIDs[document.getElementById('tileID' + pos).value] >0) {
                          if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                        var buildingMode = "build";
                        var cityId =  t.city.city.id;
                        var buildingPos = pos;
                        var buildingType = AscbuildingIDs[document.getElementById('tileID' + pos).value];
                        var buildingLevel = 0;
                        var buildingAttempts = 0;
                        var result = Tabs.build.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
                        var buildingMult = result[0];
                        var buildingTime = result[1];
                        var buildingId = AscbuildingIDs[document.getElementById('tileID' + pos).value];
                        Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);  
                        }                  
                    }
      } else {
         if  (buildingIDs[document.getElementById('tileID' + pos).value] >0) {
                          if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                        var buildingMode = "build";
                        var cityId =  t.city.city.id;
                        var buildingPos = pos;
                        var buildingType = buildingIDs[document.getElementById('tileID' + pos).value];
                        var buildingLevel = 0;
                        var buildingAttempts = 0;
                        var result = Tabs.build.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
                        var buildingMult = result[0];
                        var buildingTime = result[1];
                        var buildingId = buildingIDs[document.getElementById('tileID' + pos).value];
                        Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode); 
                        }                  
                    }
      } 
            }
    },  
    buildExtraLevels:function(rslt,buildItem){
        logit('lvl5FarmDone = ' + Options.lvl5FarmDone + ' lvl3MineDone = ' + Options.lvl3MineDone + ' lvl2BarracksDone = ' + Options.lvl2BarracksDone + ' lvl3WallDone = ' + Options.lvl3WallDone + ' lvl2WorkshopDone = ' + Options.lvl2WorkshopDone + ' lvl5CastleDone = ' + Options.lvl5CastleDone + ' buildingType =' + buildItem.buildingType)
        if (Options.lvl5FarmDone == "false" && buildItem.buildingType == "1") {
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 1;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <5; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl5FarmDone = "true";
               saveOptions();
        }
        if (Options.lvl3MineDone == "false" && buildItem.buildingType == "4") {
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 4;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <3; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl3MineDone = "true";
               saveOptions();
        }
        if (Options.lvl2BarracksDone == "false" && buildItem.buildingType == "13") {
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 13;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <2; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl2BarracksDone = "true";
               saveOptions();
        }
        if (Options.lvl3WallDone == "false" && buildItem.buildingType == "19") { //WALL
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 19;
            var buildingLevel = 1;
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <3; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl3WallDone = "true";
               saveOptions();
        }
        if (Options.lvl2WorkshopDone == "false" && buildItem.buildingType == "16") { //workshop
            var buildingMode = "build"
               var cityId = buildItem.cityId
               var time = parseInt(buildItem.buildingTime);
            var mult = parseInt(buildItem.buildingMult);
            var attempt = parseInt(buildItem.buildingAttempt);
            var buildingPos   = parseInt(buildItem.buildingPos);
            var buildingType  = 16;
            var buildingLevel = 1; //parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
            var buildingId    = rslt.buildingId;
            var buildingAttempts = 0;
            for (var bL = 1; bL <=2; bL++) {
                var queueId = Tabs.build.loaded_bQ.length;
                var result = Tabs.build.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult,buildingMode);
                Tabs.build._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
               }
               Options.lvl2WorkshopDone = "true";
               saveOptions();
        }

    },

    addFieldToQueue:function(){
        var t = Tabs.startup;
        var max = t.getCastleLevel();
        Options.lvl5FarmDone = "false";
            for (pos=100;pos<=max;pos++){
                    if  (buildingIDs[document.getElementById('tileID' + pos).value] >0) {
                        if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                        var buildingMode = "build";
                        var cityId =  t.city.city.id;
                        var buildingPos = pos;
                        var buildingType = buildingIDs[document.getElementById('tileID' + pos).value];
                        var buildingLevel = 0;
                        var buildingAttempts = 0;
                        var result = Tabs.build.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
                        var buildingMult = result[0];
                        var buildingTime = result[1];
                        var buildingId = buildingIDs[document.getElementById('tileID' + pos).value];
                        Tabs.build.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);                      
                        }
                }
            }
    },  

    paintCityGrid:function(cityDiv){
        var t = Tabs.startup;
        t.myDiv = cityDiv;
        t.where = "City";
        var counter = 0;
   	var AscCityInd = Seed.cityData.city[t.city.city.id].isPrestigeCity;
        var cityGrid = '<img src="http://koc-power-bot.googlecode.com/svn/trunk/CityTileIDs.jpg">';
   	var asccityGrid = '<img src="http://koc-power-bot.googlecode.com/svn/trunk/AscCityTileIDs.jpg">';
	var asccityfeyGrid = '<img src="http://koc-power-bot.googlecode.com/svn/trunk/AscCityFeyTileIDs.jpg">';
	var asccitybritGrid = '<img src="http://koc-power-bot.googlecode.com/svn/trunk/AscCityBritonTileIDs.jpg">';
        document.getElementById('gridPicture').innerHTML = "";
	if(AscCityInd == true) {
		varAscCityType=Seed.cityData.city[t.city.city.id].prestigeInfo.prestigeType;
		if (varAscCityType == 1) {
			document.getElementById('gridPicture').innerHTML = asccityGrid;
		} else if (varAscCityType == 2) {
			document.getElementById('gridPicture').innerHTML = asccityfeyGrid;
		} else {
			document.getElementById('gridPicture').innerHTML = asccitybritGrid;
		}
	} else {
		document.getElementById('gridPicture').innerHTML = cityGrid;
	}
        var message='<TABLE id=pbLayoutBoxes width=100% height=0%><INPUT id=showDefaults type=submit value="Load Defaults"> <INPUT id=setDefaults type=submit value="Set Defaults"> <INPUT id=loadCottages type=submit value="Load All Cottages"> <INPUT id=loadBarracks type=submit value="Load All Barracks">';

        for (k=1;k<=32;k++){
            if (k==1){
                counter++
                message += '<TD>Tile1<SELECT id=tileID1><OPTION value="Wall">Wall</option>'
            }else{
               counter++;
               message += '<TD>Tile'+k+'<SELECT id=tileID'+k+'><OPTION value="Nothing">---Select---</option>'
      if(AscCityInd == true) {
         for (kk in AsccityBuildingNames){
                           message += '<OPTION value='+kk+'>'+AsccityBuildingNames[kk]+'</option>';
                  }
      } else {
         for (kk in cityBuildingNames){
                           message += '<OPTION value='+kk+'>'+cityBuildingNames[kk]+'</option>';
         }
      }
               message += '</options>';
         if (counter % 4 == 0)message+='</tr>';
         }
        }
        document.getElementById('layoutBoxes').innerHTML = message;
            for (pos=1;pos<=32;pos++){
      if(AscCityInd == true) {
                  if (Seed.buildings['city' + t.city.city.id]["pos" + pos] != undefined){
                     document.getElementById('tileID' + pos).value = AscbuildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]];
                      document.getElementById('tileID' + pos).disabled = true;
                     logit("POS = " + pos + ' ' + AscbuildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]] + ' TYPE = ' + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]);
                  }
      } else {
                  if (Seed.buildings['city' + t.city.city.id]["pos" + pos] != undefined){
                     document.getElementById('tileID' + pos).value = buildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]];
                      document.getElementById('tileID' + pos).disabled = true;
                     logit("POS = " + pos + ' ' + buildingTypes["type"+Seed.buildings['city' +t.city.city.id]["pos"+pos][0]] + ' TYPE = ' + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]);
                  }
      }
            }
       
        document.getElementById('showDefaults').addEventListener('click', function(){
            for (pos=1;pos<=32;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = layoutOptions['pos' +pos];
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);

                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
        });
        document.getElementById('setDefaults').addEventListener('click', function(){
            for (pos=1;pos<=32;pos++){
                layoutOptions['pos'+pos] = document.getElementById('tileID' + pos).value

            }
            saveLayoutOptions();
        });
        document.getElementById('loadCottages').addEventListener('click', function(){
            for (pos=2;pos<=32;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = "Cottage";
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);

                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
        });
        document.getElementById('loadBarracks').addEventListener('click', function(){
            for (pos=2;pos<=32;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = "Barracks";
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);

                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
        });
        //code for set buttons
    },


    paintFieldGrid:function(fieldsDiv){
        var t = Tabs.startup;
        t.myDiv = fieldsDiv;
        t.where = "Field";
        var counter = 0;
        var fields = 13;
        var max = t.getCastleLevel();
        var fieldGrid = '<img src="http://koc-power-bot.googlecode.com/svn/trunk/FieldsTileIDs.jpg">';
        document.getElementById('gridPicture').innerHTML = "";
        document.getElementById('gridPicture').innerHTML = fieldGrid;
        var mess='<TABLE id=pbLayoutBoxes width=100% height=0%><INPUT id=showFieldDefaults type=submit value="Load Defaults"><INPUT id=setFieldDefaults type=submit value="Set Defaults">';
        for (k=100;k<=max;k++){
            if (k != 140 && k != 141){
                counter++
                mess += '<TD>Tile'+k+'<SELECT id=tileID'+k+'><OPTION value="Nothing">---Select---</option>'
                      for (kk in fieldBuildingNames){
                          mess += '<OPTION value='+kk+'>'+ fieldBuildingNames[kk]+'</option>';
                    }
                mess += '</options>';
            if (counter % 4 == 0)mess+='<tr>';
            }
        }
        document.getElementById('layoutBoxes').innerHTML = mess;
        for (pos=100;pos<=max;pos++){
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] != undefined){
                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
            }
  
    document.getElementById('showFieldDefaults').addEventListener('click', function(){
            for (pos=100;pos<=max;pos++){
                //logit(document.getElementById('tileID' + i).value)
                if (Seed.buildings['city' + t.city.city.id]["pos" + pos] == undefined){
                    document.getElementById('tileID' + pos).value = fieldlayoutOptions['pos' +pos];
                }else{
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0]);
                    //logit(unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0])
                    document.getElementById('tileID' + pos).value = unsafeWindow.buildingcost["bdg" + Seed.buildings['city' +t.city.city.id]["pos"+pos][0]][0];
                    document.getElementById('tileID' + pos).disabled = true;
                }
               }
    });
    document.getElementById('setFieldDefaults').addEventListener('click', function(){
            for (pos=100;pos<=max;pos++){
                fieldlayoutOptions['pos'+pos] = document.getElementById('tileID' + pos).value;
            }
            savefieldlayoutOptions();
    });
    },
  
  
    show : function(){},
    hide : function(){},
} 
var WildOptions = {
	LastSearch: 0,
	Running: false,
	WildFound: 0,
	Radius: 35,
	Interval: 60,
	Types: {
		plain: false,
		grassland: true,
		lake: true,
		hills: true,
		mountain: true,
		woods: true,
	},
	Levels: {
		1: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},
		2: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		3: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		4: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		5: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},
		6: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		7: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
		8: {0: false, 1: false, 2: false, 3: false, 4: false, 5: false, 6: false, 7: false, 8: false, 9: false, 10: false},	
	},
	TroopsW1: {
		1:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		2:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		3:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		4:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		5:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		6:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		7:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		8:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		9:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		10: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
	},
	TroopsW2: {
		1:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		2:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		3:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		4:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		5:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		6:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		7:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		8:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		9:  {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
		10: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0},
	},
};
function saveWildOptions(){ var serverID = getServerId(); setTimeout (function (){GM_setValue ('WildOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(WildOptions));}, 0);}
function readWildOptions(){ var serverID = getServerId(); s = GM_getValue ('WildOptions_'+Seed.player['name']+'_'+serverID, '[]'); if (s != null){ opts = JSON2.parse (s); for (k in opts){ if (matTypeof(opts[k]) == 'object') for (kk in opts[k]) WildOptions[k][kk] = opts[k][kk]; else if (WildOptions[k] != undefined) WildOptions[k] = opts[k]; }}}

Tabs.WildAttack = {
	tabLabel: culang.mainWildAttack,
	tabOrder: TabOptions.toWildAttack,
	myDiv: null,
	statsTimer : null,
	WildArray: {},
	mapblocks: [],
	mapDat: [],

	init: function (div) {
		var t = Tabs.WildAttack;
		t.myDiv = div;
		try {
		readWildOptions();
		if (WildOptions.Radius == undefined) WildOptions.Radius = 35;
		if (WildOptions.Radius > 45) WildOptions.Radius = 45;
		if (WildOptions.Interval == undefined) WildOptions.Interval = 60;
		var m = '<div style="max-height:' + (Options.HauteurBoite-100) +'px;overflow-y:auto"><DIV id=pbReinfMain class=pdxStat>' + culang.wildHead + '</div>';
		if (WildOptions.Running == false) {
			m += '<TD><INPUT id=WildAttSearch type=submit value="' + culang.mainWildAttack + ' = ' + culang.buttonOFF + '"></td>';
		} else {
			m += '<TD><INPUT id=WildAttSearch type=submit value="' + culang.mainWildAttack + ' = ' + culang.buttonON + '"></td>';
		}
		m += '&nbsp<INPUT id=pbWildShow type=submit class=pbButton value="' + culang.mainShow + '">&nbsp<INPUT id=pbResetWild type=submit class=pbButton value="' + culang.wildRetrySearch + '">';
		m += '&nbsp&nbsp&nbsp'+culang.wildRadius +'<INPUT id=pbWildRadius type=text value="' + WildOptions.Radius + '" style="width:30px;text-align:center;">';
		m += '&nbsp&nbsp&nbsp'+culang.wildInterval +'<INPUT id=pbWildInterval type=text value="' + WildOptions.Interval + '" style="width:30px;text-align:center;">';
		m += '<DIV id=WildStats text-align=center></div>';
		
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.wildattackStats + '</div>';
		m += '<div id=pbwildattackstats></div>';
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.wildSettingsTypes + '</div>';
		m += '<TABLE width=100%><tr>';
		for (type in WildOptions.Types) {
			var e = WildOptions.Types[type];
			m += '<td>';
			m += '<INPUT id=WildType_' + type+ ' type=checkbox unchecked=true>' + uW.g_js_strings.commonstr[type];
			m += '</td>';
		}
		m += '</tr></table>';
		
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.wildSettingsHead + '</div>';
		m += '<TABLE width=100%>';
		for (i = 0; i < Seed.cities.length; i++) {
			m += '<TR><TD>' + Seed.cities[i]["1"] + '</td>';
			for (y = 1; y <= 10; y++) m += '<TD class=WildLevelopt><INPUT id=Wildcity' + i + 'level' + y + ' type=checkbox unchecked=true>' + culang.wildTroopSelectLvl + '' + y + '</td>';
		}
		m += '</table>';
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.wildSelectTroopsHead1 + '</div>';
		m += '<TABLE width=100%><TR><TD></td>';
		for (var i = 1; i <= 12; i++) m += '<TD align=center><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg" title="' + uW.unitcost['unt' + i][0] + '"></td>';
		for (i = 1; i <= 10; i++) {
			m += '</tr><TR><TD>' + uW.g_js_strings.commonstr.level + ' ' + i + ': </td>';
			for (var j = 1; j <= 12; j++) m += '<TD align=center class=WildTroopOpt1><INPUT id="Wildlevel_w1_' + i + 'troop' + j + '" type=text size=4 maxlength=6 value="' + WildOptions.TroopsW1[i][j] + '" /></td>';
		}
		m += '</tr></table>';
		m += '<DIV id=pbReinfMain class=pdxStat>' + culang.wildSelectTroopsHead2 + '</div>';
		m += '<TABLE width=100%><TR><TD></td>';
		for (var i = 1; i <= 12; i++) m += '<TD align=center><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_' + i + '_50.jpg" title="' + uW.unitcost['unt' + i][0] + '"></td>';
		for (i = 1; i <= 10; i++) {
			m += '</tr><TR><TD>' + uW.g_js_strings.commonstr.level + ' ' + i + ': </td>';
			for (var j = 1; j <= 12; j++) m += '<TD align=center class=WildTroopOpt2><INPUT id="Wildlevel_w2_' + i + 'troop' + j + '" type=text size=4 maxlength=6 value="' + WildOptions.TroopsW2[i][j] + '" /></td>';
		}
		m += '</tr></table>';
		m += '<span class=boldRed><u>' + culang.mainImportant + '</u></span>: <span class=helpText>' + culang.wildHeadTroopsNote + '</span></div>';

		t.myDiv.innerHTML = m;

		for (i = 0; i < Seed.cities.length; i++)
			for (w = 1; w <= 10; w++) ById('Wildcity' + i + 'level' + w).checked = WildOptions.Levels[i + 1][w];
		ById('pbResetWild').addEventListener('click', t.ResetWildData, false);
		var element_class = document.getElementsByClassName('WildLevelopt');
		for (k = 0; k < element_class.length; k++) element_class[k].addEventListener('click', t.saveLevelOptions, false);
		var element_class = document.getElementsByClassName('WildTroopOpt1');
		for (k = 0; k < element_class.length; k++) element_class[k].addEventListener('change', t.saveTroopOptions, false);
		var element_class = document.getElementsByClassName('WildTroopOpt2');
		for (k = 0; k < element_class.length; k++) element_class[k].addEventListener('change', t.saveTroopOptions, false);
		for (type in WildOptions.Types) {
			var e = ById('WildType_' + type).checked = WildOptions.Types[type];
			ById('WildType_' + type).addEventListener('click', function() {
				var type = this.id.split('_')[1];
				WildOptions.Types[type] = ById('WildType_' + type).checked;
				saveWildOptions();
			}, false);
		}
		ById('WildAttSearch').addEventListener('click', function () {
			t.toggleWildState()
		}, false);
		ById('pbWildShow').addEventListener('click', function () {
			t.ShowWildArray()
		}, false);
		ById('pbWildRadius').addEventListener('change', function () {
			var value = parseIntNan(ById('pbWildRadius').value);
			if (value < 20) value = 20;
			if (value > 45) value = 45;
			ById('pbWildRadius').value = value;
			WildOptions.Radius = value;
			saveWildOptions();
		}, false);
		ById('pbWildInterval').addEventListener('change', function () {
			var value = parseIntNan(ById('pbWildInterval').value);
			if (value < 20) value = 20;
			if (value > 240) value = 240;
			ById('pbWildInterval').value = value;
			WildOptions.Interval = value;
			saveWildOptions();
		}, false);
		
		var now = unixTime();
		ById('WildStats').innerHTML = "<b>" + culang.wildLastSearch + "</b> <i><span class='boldRed'>" + FullDateTime(WildOptions.LastSearch) + "</span></i> <b>" + culang.wildLastSearch2 + "</b> <i><span class='boldRed'>" + WildOptions.WildFound + "</span> " + culang.wildLastSearch3 + "</i>";
		if ((WildOptions.LastSearch + (WildOptions.Interval * 60)) < now && WildOptions.Running) t.ResetWildData();
		else {
			for (i = 0; i < Seed.cities.length; i++) {
				var helpArray = JSON2.parse(GM_getValue('WildAttack_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), "[]"));
				t.WildArray[i] = [];
				if (helpArray) t.WildArray[i] = helpArray.sort(function sortBarbs(a, b) {
					a = a['D'];
					b = b['D'];
					return a == b ? 0 : (a < b ? -1 : 1);
				});
			}
		}
		t.statsTimer = setInterval(t.showStats, 1000);
	} catch (ex) {
					alert('33367/ '+ ex.name + ': ' + ex.message + " @" + ex.lineNumber);
	}
	},
	showStats: function() {
		var t = Tabs.WildAttack;
		try {
		var m = '<table width=100%><tr>';
		for (i = 0; i < Seed.cities.length; i++) {
			m += '<td width=13% align=center><b>' + Cities.cities[i].name + '</b><br>' + t.WildArray[i].length + '</td>';
		}
		m += '</tr></table>';
		} catch(ex) {
			ById('pbwildattackstats').innerHTML = ex.name +': '+ ex.message + " @"+ ex.lineNumber;
		}
		ById('pbwildattackstats').innerHTML = m;
	},
	saveLevelOptions: function () {
		for (i = 0; i < Seed.cities.length; i++) {
			WildOptions.Levels[i + 1][0] = false;
			for (w = 1; w <= 10; w++) {
				var ele = ById('Wildcity' + i + 'level' + w);
				WildOptions.Levels[i + 1][w] = ele.checked;
				if (ele.checked) WildOptions.Levels[i + 1][0] = true;
			}
		}
		saveWildOptions();
	},
	saveTroopOptions: function () {
		for (i = 1; i <= 10; i++)
			for (w = 1; w <= 12; w++) {
				WildOptions.TroopsW1[i][w] = ById('Wildlevel_w1_' + i + 'troop' + w).value;
				WildOptions.TroopsW2[i][w] = ById('Wildlevel_w2_' + i + 'troop' + w).value;
			}
		saveWildOptions();
	},
	toggleWildState: function (obj) {
		var t = Tabs.WildAttack;
		var now = unixTime();
		obj = ById('WildAttSearch');
		if (WildOptions.Running == true) {
			WildOptions.Running = false;
			obj.value = culang.mainWildAttack + " = " + culang.buttonOFF;
			ClearMarchQueue("WildW1");
			ClearMarchQueue("WildW2");
			saveWildOptions();
		} else {
			if ((WildOptions.LastSearch + (WildOptions.Interval * 60)) < now) t.ResetWildData();
			WildOptions.Running = true;
			obj.value = culang.mainWildAttack + " = " + culang.buttonON;
			saveWildOptions();
		}
	},
	ShowWildArray: function () {
		var t = Tabs.WildAttack;
		var wtype = "";
		var wtext = "";
		var max = 50;
		var m = '<b>' + culang.wildmaxinfo + '</b><br>';
		m += '<TABLE id=pbWild width=100% class=pdxTab>';
		for (i = 0; i < Seed.cities.length; i++) {
			if (t.WildArray[i].length > 0) {
				m += '<TR><TD colspan=6 style=\'background: #335577;\' align=center><B><FONT color=white>' + Seed.cities[i][1] + ': </font></b></td></tr>';
				var counter = 0;
				for (var k in t.WildArray[i]) {
					counter++;
					if (counter >= max) break;
					if (t.WildArray[i][k].D) {
						if (t.WildArray[i][k].L >= 1 && t.WildArray[i][k].L <= 3) var Tlevel = 1;
						if (t.WildArray[i][k].L >= 4 && t.WildArray[i][k].L <= 6) var Tlevel = 4;
						if (t.WildArray[i][k].L >= 7) var Tlevel = 7;
						m += '<TR><TD><a href="javascript:void(0)" onclick="clickKoords(event)" class="coordinateLink">(' + t.WildArray[i][k].X + ',' + t.WildArray[i][k].Y + ')</a></td>';
						if (t.WildArray[i][k].T == 10) {wtype = "grasslands"; wtext = uW.g_js_strings.commonstr.grassland;}
						if (t.WildArray[i][k].T == 11) {wtype = "lake"; wtext = uW.g_js_strings.commonstr.lake;}
						if (t.WildArray[i][k].T == 20) {wtype = "forest"; wtext = uW.g_js_strings.commonstr.woods;}
						if (t.WildArray[i][k].T == 30) {wtype = "hills"; wtext = uW.g_js_strings.commonstr.hills;}
						if (t.WildArray[i][k].T == 40) {wtype = "mountain"; wtext = uW.g_js_strings.commonstr.mountain;}
						if (t.WildArray[i][k].T == 50) {wtype = "plains"; wtext = uW.g_js_strings.commonstr.plain;}
						m += '<td>'+wtext+'</td>';
						m += '<TD width=50px><img width=50px src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/'+wtype+'_lvl' + Tlevel + '.png"></td>';
						m += '<TD>' + culang.wildTroopSelectLvl + ' ' + t.WildArray[i][k].L + '</td><TD>' + culang.wildTroopSelectDist + ' ' + t.WildArray[i][k].D + '</td></tr>';
					}
				}
			}
		}
		var pop = new CPopup('WildArray', 0, 0, 450, 550, true);
		pop.centerMe(mainPop.getMainDiv());
		pop.getMainDiv().innerHTML = '<DIV style="height:500px;overflow-y:auto">' + m + '</div>';
		pop.getTopDiv().innerHTML = '<div class="popupBanner">' + culang.wildPopupHead + '</div>';
		pop.show(true);
	},
	ResetWildData: function () {
		var t = Tabs.WildAttack;
		for (i = 0; i < Seed.cities.length; i++) GM_deleteValue('WildAttack_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), "[]")
		var ToSearch = [];
		var now = unixTime();
		for (i = 0; i < Seed.cities.length; i++) {
			AllEmpty = true;
			t.WildArray[i] = [];
			for (var y = 1; y <= 10; y++)
				if (WildOptions.Levels[i + 1][y]) AllEmpty = false;
			if (!AllEmpty) ToSearch.push(i);
		}
		if (ToSearch.length > 0) {
			WildOptions.LastSearch = now;
			WildOptions.WildFound = 0;
			saveWildOptions();
			t.mapblocks = [];
			ById('WildStats').innerHTML = '' + culang.searchStartSearching + ': <span id="SearchWild"></span> <span id="MapSearchActiveWild"></span>';
			for (i = 0; i < ToSearch.length; i++) {
				X = parseInt(Seed.cities[ToSearch[i]][2]);
				Y = parseInt(Seed.cities[ToSearch[i]][3]);
				t.MakeBlocks(X, Y, (ToSearch[i] + 1), (i + 1), ToSearch.length);
			}
			t.doSearch();
		}
	},
	MakeBlocks: function (getX, getY, city, i, length) {
		var t = Tabs.WildAttack;
		var blocks = [];
		var xx = 0;
		var yy = 0;
		var blockcounter = 0;
		for (x = (getX - WildOptions.Radius); x <= (getX + WildOptions.Radius); x += 5) {
			for (y = (getY - WildOptions.Radius); y <= (getY + WildOptions.Radius); y += 5) {
				xx = x;
				yy = y;
				if (x > 750) xx -= 750;
				if (y > 750) yy -= 750;
				if (x < 0) xx += 750;
				if (y < 0) yy += 750;
				blocks.push("bl_" + xx + "_bt_" + yy);
				blockcounter++;
			}
		}
		//Aufteilen in kleinere Mengen a 15 blocks
		var max = ~~(blockcounter/searchblocks) + 1;
		var blo = [];
		for (var split = 0; split < max; split++) {
			blo = [];
			for (var z = 0; z < searchblocks; z++) {
				if (blocks.length > 0) {
					blo.push(blocks[0]);
					blocks.shift();
				}
			}
			var o = {
				'x'	: getX,
				'y'	: getY,
				'c'	: city,
				'i'	: i,
				'l'	: length,
				'm' : max,
				's' : split+1,
				'b'	: blo,
			};
			t.mapblocks.push(o);		
		}
	},
	doSearch: function () {
		var t = Tabs.WildAttack;
		if (MapSearchActive == "") {
			MapSearchActive = culang.mainWildAttack;
		} 	
		if (MapSearchActive != culang.mainWildAttack)  {
			var rep = {
				'tab' : MapSearchActive,
			};
			ById('MapSearchActiveWild').innerHTML = culang.MapSearchActive.mreplace(rep);
			setTimeout(t.doSearch, 5000);
			return;
		} else if (t.mapblocks.length > 0) {
			ById('MapSearchActiveWild').innerHTML = '';
		}
		if (t.mapblocks.length > 0) {
			//Suchdaten auslesen
			var mdata = t.mapblocks[0];
			var blocks = mdata.b;
			var xx = mdata.x;
			var yy = mdata.y;
			var city = mdata.c;
			var i = mdata.i;
			var length = mdata.l;
			var max = mdata.m;
			var s = mdata.s;
		} else {
			//Keine weitern Suchdaten
			MapSearchActive = "";
			return;
		}
		
		var params = uW.Object.clone(uW.g_ajaxparams);
		params.blocks = blocks;
		new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchMapTiles.php" + uW.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok) {
					if (rslt.error_code == 9) {
						//Map Error
						ById('MapSearchActiveWild').innerHTML = 'Map Error (60 Sec)';
						setTimeout(t.doSearch, 61000);
						return;
					}	
					ById('SearchWild').innerHTML = '('+i+'/'+length+') - ('+s+'/'+max+')';
					//Startet die Teilsuche?
					if (s == 1) t.mapDat = [];
										
					for (y in rslt.data) {
						var e = rslt.data[y];
						if ((WildOptions.Types.grassland && e.tileType == 10) ||
								(WildOptions.Types.lake && e.tileType == 11) ||
								(WildOptions.Types.woods && e.tileType == 20) ||
								(WildOptions.Types.hills && e.tileType == 30) ||
								(WildOptions.Types.mountain && e.tileType == 40) ||
								(WildOptions.Types.plain && e.tileType == 50)) {
							if (WildOptions.Levels[city][parseInt(e.tileLevel)]) {
								//Frei?
								if (e.tileUserId == null && e.misted == false) {
									t.mapDat.push({
										X: parseInt(e.xCoord),
										Y: parseInt(e.yCoord),
										L: parseInt(e.tileLevel),
										T: parseInt(e.tileType),
										D: distance(xx, yy, parseInt(e.xCoord), parseInt(e.yCoord)),									
									});
									WildOptions.WildFound++;
								}
							}
						}
					}
					saveWildOptions();
					//Teilsuche
					if (s == max) {
						//Teilsuche in der Stadt beendet
						GM_setValue('WildAttack_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.mapDat));
						var helpArray = JSON2.parse(GM_getValue('WildAttack_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), "[]"));
						if (helpArray) t.WildArray[(city - 1)] = helpArray.sort(function sortBarbs(a, b) {
							a = a['D'];
							b = b['D'];
							return a == b ? 0 : (a < b ? -1 : 1);
						});
					}
					if (i == length && s == max) {
						//Suche Beendet
						ById('WildStats').innerHTML = "<b>" + culang.wildLastSearch + "</b> <i><span class='boldRed'>" + FullDateTime(WildOptions.LastSearch) + "</span></i> <b>" + culang.wildLastSearch2 + "</b> <i><span class='boldRed'>" + WildOptions.WildFound + "</span> " + culang.wildLastSearch3 + "</i>";
					}
				} else {
					actionLog(culang.mainWildAttack,inspect(rslt,4));
				}
				t.mapblocks.splice(0,1);
				setTimeout(t.doSearch, 500);
			},
			onFailure: function (transport) {
				t.mapblocks.splice(0,1);
				setTimeout(t.doSearch, 500);
			},
		});
	},
	CalcMax: function (city, troop) {
		var t = Tabs.WildAttack;
		var rinfo = getRallypointInfo(city);
		var maxsend = rinfo.maxMarchSize;
		//if (maxsend > Seed.units["city" + city]["unt" + troop]) maxsend = 0;
		return maxsend;
	},
	show: function () {
		var t = Tabs.WildAttack;
		clearInterval(t.statsTimer);
		t.statsTimer = setInterval(t.showStats, 1000);
	},
	hide: function () {
		var t = Tabs.WildAttack;
		clearInterval(t.statsTimer);
	},
	doMarch: function (cityID, i) {
		var t = Tabs.WildAttack;
		var now = unixTime();
		//Neu suchen?
		if ((WildOptions.LastSearch + (WildOptions.Interval * 60)) < now) {
			t.ResetWildData();
			return false;
		}
		//Keine Koordinaten
		if (t.WildArray[i].length == 0) {
			var rep = {
				'city' : Cities.byID[cityID].name,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr1.mreplace(rep));
			return false;
		}
		//Soll Wildnis dieses Levels angegriffen werden?
		var Level = parseInt(t.WildArray[i][0].L);
		if (!WildOptions.Levels[i + 1][Level]) return;
		//Sind freie Wildnisslots in der Stadt vorhanden?
		var totWilds = 0;
		var dat = Seed.wilderness['city'+ cityID];
		if (dat!=null && matTypeof(dat)=='object')
			for (k in dat)
				++totWilds;
		var nivcastle = parseIntNan(Seed.buildings['city'+cityID].pos0[1]);
		var castle = nivcastle;
		if (nivcastle==11) castle=12;
		if (nivcastle==12) castle=14;
		if (totWilds < castle) {
			var rep = {
				'city' : Cities.byID[cityID].name,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr2.mreplace(rep));
			return false;
		}
		//Truppen MAX Kalkulation fuer 1. Welle
		var troopsW1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
		for (y = 1; y <= 12; y++) {
			if (WildOptions.TroopsW1[Level][y] == "MAX") {
				var total = 0;
				for (var yy = 1; yy <= 12; yy++)
					if (y != yy) total += parseInt(WildOptions.TroopsW1[Level][yy]);
				troopsW1[y] = t.CalcMax(cityID, y) - total;
			} else troopsW1[y] = WildOptions.TroopsW1[Level][y];
		}
		//Genug Truppen in der Stadt?
		var ok = true;
		for (y = 1; y <= 12; y++) {
		 if (parseIntNan(Seed.units["city" + cityID]['unt'+y]) < troopsW1[y]) ok = false;
		}
		if (ok == false) {
			var rep = {
				'city' : Cities.byID[cityID].name,
				'level' : t.WildArray[i][0].L,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr3.mreplace(rep));
			return false;
		}
		//Truppen MAX Kalkulation fuer 2. Welle
		var troopsW2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
		for (y = 1; y <= 12; y++) {
			if (WildOptions.TroopsW2[Level][y] == "MAX") {
				var total = 0;
				for (var yy = 1; yy <= 12; yy++)
					if (y != yy) total += parseInt(WildOptions.TroopsW2[Level][yy]);
				troopsW2[y] = t.CalcMax(cityID, y) - total;
			} else troopsW2[y] = WildOptions.TroopsW2[Level][y];
		}
		//Genug Truppen in der Stadt?
		var ok = true;
		for (y = 1; y <= 12; y++) {
		 if (parseIntNan(Seed.units["city" + cityID]['unt'+y]) < troopsW2[y]) ok = false;
		}
		if (ok == false) {
			var rep = {
				'city' : Cities.byID[cityID].name,
				'level' : t.WildArray[i][0].L,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr4.mreplace(rep));
			return false;
		}

		//Sind Truppen angegeben fuer Welle 1?
		var firstwave = true;		
		var W1total = 0;
		for (y = 1; y <= 12; y++) {
		 W1total += troopsW1[y];
		}
		if (W1total == 0) {
			firstwave = false;
			/*
			var rep = {
				'level' : t.WildArray[i][0].L,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr5.mreplace(rep));
			return false;
			*/
		}
		//Sind Truppen angegeben fuer Welle 2?
		var W2total = 0;
		for (y = 1; y <= 12; y++) {
		 W2total += troopsW2[y];
		}
		if (W2total == 0) {
			var rep = {
				'level' : t.WildArray[i][0].L,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr6.mreplace(rep));
			return false;
		}
		//Sind 2 Slots im Sammelplatz frei?
		var rinfo = getRallypointInfo(cityID);
		if ((firstwave && rinfo.freeSlots - Options.RPClip < 2) ||
				(!firstwave && rinfo.freeSlots - Options.RPClip < 1)
			 ) {
			/*
			var rep = {
				'city' : Cities.byID[cityID].name,
			};
			actionLog(culang.mainWildAttack,culang.wildAttackErr7.mreplace(rep));
			*/
			return false;
		}
		//Welle 1 in Warteschlange aufnehmen
		if (firstwave) {
			MarchQueue[i + 1].push({
				what: "WildW1",
				city: cityID,
				action: 4,
				targetX: t.WildArray[i][0].X,
				targetY: t.WildArray[i][0].Y,
				1: troopsW1[1],
				2: troopsW1[2],
				3: troopsW1[3],
				4: troopsW1[4],
				5: troopsW1[5],
				6: troopsW1[6],
				7: troopsW1[7],
				8: troopsW1[8],
				9: troopsW1[9],
				10: troopsW1[10],
				11: troopsW1[11],
				12: troopsW1[12],
				13: 0,
				14: 0,
				15: 0,
				16: 0,
			});
		}
		//Welle 2 in Warteschlange aufnehmen
		MarchQueue[i + 1].push({
			what: "WildW2",
			city: cityID,
			action: 4,
			targetX: t.WildArray[i][0].X,
			targetY: t.WildArray[i][0].Y,
			1: troopsW2[1],
			2: troopsW2[2],
			3: troopsW2[3],
			4: troopsW2[4],
			5: troopsW2[5],
			6: troopsW2[6],
			7: troopsW2[7],
			8: troopsW2[8],
			9: troopsW2[9],
			10: troopsW2[10],
			11: troopsW2[11],
			12: troopsW2[12],
			13: 0,
			14: 0,
			15: 0,
			16: 0,
		});
		//Koordinate loeschen
		t.WildArray[i].splice(0, 1);
		GM_setValue('WildAttack_' + Seed.player['name'] + '_city_' + (i + 1) + '_' + getServerId(), JSON2.stringify(t.WildArray[i]));
		return true;
	},

}


//
// ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?Ãƒâ€¦Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?Ãƒâ€š?
// ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡   KOC POWER - EMH                                 ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡
// ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬?Ãƒâ€¹Ã…â€œ
//	